I am getting wrong result using below method.
public double evaluate(final double leftOperand, final double rightOperand) {
Double rtnValue = new Double(leftOperand * rightOperand);
return rtnValue.doubleValue();
}
Enter Parameter value are: leftOperand= 100 and rightOperand=2.55
I am getting Wrong answer: 254.99999999999997
The correct answer is a 255.0
Use BigDecimal
BigDecimal bd = new BigDecimal("100");
BigDecimal ans = bd.multiple(new BigDecimal("2.55"));
System.out.println(ans);
See Also
Working IDE One demo
Retain precision with double in Java
This is due to floating point precision problem. It is impossible to represent every rational number within 64 bits. The numbers are stored within the IEEE 754 format.
If you are creating a game, this is more than good enough, even float will do. But if you are doing some finance, it should be correct. Then you can use java.math.BigDecimal
. It is much slower than double
but it is correct. And it takes much more memory, since you have an exact value in memory. Here is a nice tutorial on how to use BigDecimal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With