0

In Java when I have used double numbers and when the values are as follows, the result is not correct. I can round this, but it will need to change in several places. What is the reason to have this result.

public static void main(String[] args) {
    double a=300.0;
    double b=24.08;
    System.out.println(a*b);
}

The result is 7223.999999999999.

But the actual result should have been 7224.

But why?

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
Buddhika Ariyaratne
  • 2,339
  • 6
  • 51
  • 88
  • 1
    Look here : http://stackoverflow.com/questions/8253789/double-calculation-producing-odd-result ... use BigDecimal – pL4Gu33 Feb 26 '14 at 16:10
  • 2
    Aaaand again: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Dave Newton Feb 26 '14 at 16:11
  • If you want exact floating point calculation, use `BigDecimal`. – fge Feb 26 '14 at 16:13
  • @fge: `BigDecimal` has its own issues, like trying to represent `1/3`. :-) But yes, if you want precision to a given fixed number of decimal places in a human-oriented way, `BigDecimal`'s the way go to. :-) – T.J. Crowder Feb 26 '14 at 16:14
  • 1
    @fge: When I see this question (again and again :-( ) and see the recommendataion to use `BigDecimal`, I always cringe a little: The people who are *asking* this question are probably the same who then say: "Man, Java sux", and blindly replace all their floating point computations (which are perfectly valid in nearly *all* cases!) with `BigDecimal`. While the recommendation itself is not "technically wrong", it should probably elaborated a little. So @Buddhika Ariyaratne: In most cases, this lack of precision does not matter. If you think that it matters, explain why you think it does – Marco13 Feb 26 '14 at 16:39
  • We have directly displayed the output to the end users and they are really worried as they get this sort of number instead of actual value they get from doing it manually. I overcame the issue after rounding the output in GUI. – Buddhika Ariyaratne Feb 26 '14 at 23:58

0 Answers0