问题:
BigDecimal countTurnover = new BigDecimal(double val); //不靠谱
解释:
首先是BigDecimal的double参数构造,在官方JDK文档中对这个构造是这么描述的:
public BigDecimal(double val)
Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer.
Notes:
The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.
Parameters:
val - double value to be converted to BigDecimal.
Throws:
NumberFormatException - if val is infinite or NaN.
翻译:
1,BigDecimal(double val)构造,用double当参数来构造一个BigDecimal对象。
2,但是这个构造不太靠谱(unpredictable),你可能以为BigDecimal(0.1)就是妥妥的等于0.1,但是你以为你以为的就是你以为的?还真不是,BigDecimal(0.1)这货实际上等于0.1000000000000000055511151231257827021181583404541015625,因为准确的来说0.1本身不能算是一个double(其实0.1不能代表任何一个定长二进制分数)。
3,BigDecimal(String val)构造是靠谱的,BigDecimal(“0.1”)就是妥妥的等于0.1,推荐大家用这个构造。
4,如果你非得用一个double变量来构造一个BigDecimal,没问题,我们贴心的提供了静态方法valueOf(double),这个方法跟new Decimal(Double.toString(double))效果是一样的。
解决方法: Double.toString(c)
public static void main(String[] args) {
float a=57.3f;
BigDecimal decimalA=new BigDecimal(a);
System.out.println(decimalA); // 57.299999237060546875
double b=57.3;
BigDecimal decimalB=new BigDecimal(b);
System.out.println(decimalB); // 57.2999999999999971578290569595992565155029296875
double c=57.3;
BigDecimal decimalC=new BigDecimal(Double.toString(c));
System.out.println(decimalC); //57.3
double d=57.3;
BigDecimal decimalD=BigDecimal.valueOf(d);
System.out.println(decimalD); // 57.3
}