数据类型转换:
包括Double,Float,Integer,Long,String等类型转换成BigDecimal
public static void testDecimal(){
//new BigDecima()
System.out.println(new BigDecimal("0.03"));//0.03
System.out.println(new BigDecimal(3));//3
System.out.println(new BigDecimal(3L));//3
System.out.println(new BigDecimal(0.03));//0.0299999999999999988897769753748434595763683319091796875
System.out.println(new BigDecimal(0.03f));//0.02999999932944774627685546875
//BigDecimal.valueOf(double val)
//BigDecimal.valueOf(long val)
System.out.println(BigDecimal.valueOf(3L));//3
System.out.println(BigDecimal.valueOf(0.03));//0.03
System.out.println(BigDecimal.valueOf(0.03f));//0.029999999329447746
System.out.println(BigDecimal.valueOf(1000L));//100
// 使用setScale()精确小数位
System.out.println(new BigDecimal(0.03).setScale(4,BigDecimal.ROUND_HALF_UP));//0.300
System.out.println(new BigDecimal(0.99f).setScale(4,BigDecimal.ROUND_HALF_UP));//0.0300
System.out.println(BigDecimal.valueOf(0.03f).setScale(4,BigDecimal.ROUND_HALF_UP));//0.0300
}
Rounding Mode精确小数位数(7种模式):
public static void testRoundingMode(){
// 1.BigDecimal.ROUND_UP 直接进位
System.out.println(BigDecimal.valueOf(3.51).setScale(1,BigDecimal.ROUND_UP));// 3.6
// 2.BigDecimal.ROUND_DOWN 直接退位
System.out.println(BigDecimal.valueOf(3.57).setScale(1,BigDecimal.ROUND_DOWN));// 3.5
// 3.BigDecimal.ROUND_CEILING
// 正数时同ROUND_UP,负数时同ROUND_DOWN(绝对值进位)
System.out.println(BigDecimal.valueOf(3.51).setScale(1,BigDecimal.ROUND_CEILING));// 3.6
System.out.println(BigDecimal.valueOf(-3.57).setScale(1,BigDecimal.ROUND_CEILING));// -3.5
// 4.ROUND_HALF_UP 四舍五入
System.out.println(BigDecimal.valueOf(3.55).setScale(1,BigDecimal.ROUND_HALF_UP));// 3.6
// 5.ROUND_HALF_DOWN 五舍六入
System.out.println(BigDecimal.valueOf(3.55).setScale(1,BigDecimal.ROUND_HALF_DOWN));// 3.5
System.out.println(BigDecimal.valueOf(3.56).setScale(1,BigDecimal.ROUND_HALF_DOWN));// 3.6
// 6.ROUND_HALF_EVEN
// 前一位是奇数,则同ROUND_HALF_UP
System.out.println(BigDecimal.valueOf(3.55).setScale(1,BigDecimal.ROUND_HALF_EVEN));//3.6
System.out.println(BigDecimal.valueOf(3.55).setScale(1,BigDecimal.ROUND_HALF_UP));//3.6
System.out.println(BigDecimal.valueOf(3.55).setScale(1,BigDecimal.ROUND_HALF_DOWN));//3.5
// 前一位是偶数,则同ROUND_HALF_DOWN
System.out.println(BigDecimal.valueOf(4.665).setScale(2,BigDecimal.ROUND_HALF_EVEN));//4.66
System.out.println(BigDecimal.valueOf(4.665).setScale(2,BigDecimal.ROUND_HALF_UP));//4.67
System.out.println(BigDecimal.valueOf(4.665).setScale(2,BigDecimal.ROUND_HALF_DOWN));//4.66
}