5

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

bNd
  • 7,512
  • 7
  • 39
  • 72
  • 4
    Obligatory "What Every Computer Scientist Should Know About Floating-Point Arithmetic"-link: http://docs.sun.com/source/806-3568/ncg_goldberg.html – Jacob Jul 31 '12 at 10:11
  • 1
    What *exact* value do you believe your value of "2.55" has? – Jon Skeet Jul 31 '12 at 10:11
  • @JonSkeet: Even if you know the exact value of both 2.55 and 100.0, the answer would be wrong... – Martijn Courteaux Jul 31 '12 at 10:17
  • @MartijnCourteaux: I don't believe that's the case. When both source operands and the target value are all exactly representable, I *believe* IEEE-754 guarantees that the result will be "correct". – Jon Skeet Jul 31 '12 at 10:21
  • duplicate of http://stackoverflow.com/questions/6075422/unexpected-decimal-result?lq=1 – Ajay George Jul 31 '12 at 10:23
  • @JonSkeet: I wrote a test case: http://ideone.com/1Sazg What do you think? I think that it isn't correct, as I though. But I'm not sure. – Martijn Courteaux Jul 31 '12 at 10:33
  • @MartijnCourteaux: You're still using 2.55d, which *isn't* exactly 2.55. It's not clear what you think is "wrong" in the computations given there. – Jon Skeet Jul 31 '12 at 11:02
  • @MartijnCourteaux yes it is not working for double values. Required to convert double to string for both parameter i.e String.valueOf(leftOperand); for given BigDecimal solution. – bNd Jul 31 '12 at 11:22
  • @Bhumika: is it the part of Expression Evaluator ?. :D – Hardik Mishra Jul 31 '12 at 11:41

3 Answers3

4

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.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
4

Use BigDecimal

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

See Also

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
-1

Using Math.round().

public static double evaluate(final double leftOperand, final double rightOperand) {
        Double rtnValue = new Double(leftOperand * rightOperand);
        return Math.round(rtnValue.doubleValue());
    }
Mohammod Hossain
  • 4,134
  • 2
  • 26
  • 37