background
In the blog disgusting 0.5 rounding problem in the article see a question about 0.5 not correct rounding. The main thing is that after the double conversion to BigDecimal, rounding does not get the correct result:
public class Bigdecimaltest {public
static void Main (string[] args) {
double d = 301353.05;
BigDecimal decimal = new BigDecimal (d);
System.out.println (decimal);//301353.0499999999883584678173065185546875
System.out.println ( Decimal.setscale (1, roundingmode.half_up));//301353.0
}
}
The results of the output are:
301353.0499999999883584678173065185546875
301353.0
This result is obviously not what we expect, and what we want is to get 301353.1.
reason
Allow a discerning eye to see the other problem--theBigDecimal constructor public BigDecimal (double val) loses the precision of the double parameter , which leads to the wrong result. The key to the problem is that the BigDecimal constructor public BigDecimal (double val) loses the precision of the double parameter.
the way to solve it
Because the above found the reason, so also very good solution. As long as the loss of the precision of double to BigDecimal is prevented, there is no problem.
1) It's easy to think of the first workaround: Use the BigDecimal constructor with string as the parameter: public BigDecimal (string val) instead.
The following are the landlord and the message of other discussions
1 L is right, the precision of floating-point number is limited, it is possible to lose precision in the operation, so Java provides bigdecimal to accurately decimal representation and calculation. But it cannot be said that BigDecimal will lose the precision of double, which is absolutely wrong.
In your example, the 301353.05-generated BigDecimal object prints out not 301353.05 but 301353.0499999999883584678173065185546875, because the latter is the value of the 301353.05 memory bit pattern, which is the Java The double type can represent the value closest to 301353.05. That is to say, 301353.05 is the same in memory.
String.valueof () seems to have no loss of precision because it will eventually invoke the doubled () method, which will approximate the internal value of double to make the printed string look more "reasonable". For example, the computer will think that 301353.04999xxxxx is more likely to be 301353.05, so the result is approximate to it. Look at the method description for double.tostring (double) in the JDK documentation.
I can write a counter example similar to yours to illustrate that string.valueof () is not as "accurate" as you think.
1 2 3 |
Double d = 301353 0499999999883584678173065185546875d; System.out.println (string.valueof (d)); System.out.println (New Java.math.BigDecimal (d)); |
The first sentence is 301353.05, but the second sentence prints out the exact value of D. With your own example, which one do you think is more accurate?