System.out.println(new BigDecimal(“0.8323”));
System.out.println(BigDecimal.valueOf(0.8323));
System.out.println(new BigDecimal(0.8323));
System.out.println("=======================");
System.out.println(new BigDecimal(“892320”));
System.out.println(BigDecimal.valueOf(892320));
System.out.println(new BigDecimal(892320));
测试结果:
从结果可以看出,long 类型,new BigDecimal 和value of 结果没有区别,浮点型结果就不一样了
查看源码
public static BigDecimal valueOf(double val) {
// Reminder: a zero double returns '0.0', so we cannot fastpath
// to use the constant ZERO. This might be important enough to
// justify a factory approach, a cache, or a few private
// constants, later.
return new BigDecimal(Double.toString(val));
}
public static BigDecimal valueOf(long val) {
if (val >= 0 && val < zeroThroughTen.length)
return zeroThroughTen[(int)val];
else if (val != INFLATED)
return new BigDecimal(null, val, 0, 0);
return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
}
new BigDecimal
public BigDecimal(String val) {
this(val.toCharArray(), 0, val.length());
}
public BigDecimal(double val) {
this(val,MathContext.UNLIMITED);
}
public BigDecimal(int val) {
this.intCompact = val;
this.scale = 0;
this.intVal = null;
}
从源码中可以看出,String 和long类型直接把值返回,而浮点型的数字转换
BigDecimal.valueof(0.2) 等同于new BigDecimal(“0.2”) 结果是一样的
new BigDecimal(0.2) 又