Reputation: 7630
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
Upvotes: 5
Views: 1574
Reputation: 4114
Using Math.round().
public static double evaluate(final double leftOperand, final double rightOperand) {
Double rtnValue = new Double(leftOperand * rightOperand);
return Math.round(rtnValue.doubleValue());
}
Upvotes: -1
Reputation: 68847
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.
Upvotes: 4
Reputation: 240860
Use BigDecimal
BigDecimal bd = new BigDecimal("100");
BigDecimal ans = bd.multiple(new BigDecimal("2.55"));
System.out.println(ans);
See Also
Upvotes: 4