Getting the wrong result for evaluating 100 * 2.55 values

I am getting the wrong result using the method below.

public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); return rtnValue.doubleValue(); } 

Enter the parameter value: leftOperand = 100 and rightOperand = 2.55

I get the wrong answer: 254.999999999999999997

Correct answer: 255.0

+5
java
Jul 31 '12 at 10:09
source share
3 answers

Use BigDecimal

 BigDecimal bd = new BigDecimal("100"); BigDecimal ans = bd.multiple(new BigDecimal("2.55")); System.out.println(ans); 

see also

+4
Jul 31 '12 at 10:10
source share

This is due to the problem of floating point precision . It is impossible to imagine every rational number within 64 bits. Numbers are stored in IEEE 754 format.

If you create a game, this is more than enough, even a float will do. But if you are in finance, this should be right. Then you can use java.math.BigDecimal . This is much slower than double , but it is correct. And it takes up a lot more memory, since you have the exact value in memory. Here is a good tutorial on using BigDecimal .

+4
Jul 31 '12 at 10:10
source share

Using Math.round ().

 public static double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); return Math.round(rtnValue.doubleValue()); } 
-one
Jul 31 '12 at 10:28
source share



All Articles