1

Sum of the double value is showing wrong result.

public static void main(String[] args) {
        Double d =0.0;
        d += 300.10;
        d += 300.10;
        d += 300.10;
        d += 600.19;

        System.out.println(d);
    }

Output is : 1500.4900000000002

Which is incorrect output. If you do addition in excel or normal calculator total value is 1500.49. But why java is adding extra decimal value 00000000002 for double only.

I have tested in Java 1.6 and 1.7 environments and found that if total double value falls in 1000.00 to 2000.00 then extra decimals 00000000001 is showing in java 1.6. But in Java 1.7 total double value falls in 1500.00 to 3000.00 then extra decimals 00000000002.

Why it is behaving for double value in Java?. Can anyone help me on this?

Thanks Vijaya Kumar Rasala IT-Engineer Palair,Khammam,Andhra Pradesh

user3020135
  • 31
  • 1
  • 6

4 Answers4

4

Because floating point numbers are never, ever, ever exact on modern machines.

You should read up on the IEEE 754 floating point number format to see why we can't have 100% precision (or at least, not with this representation).

As mentioned by João Silva, you can format your number so it looks correct by using printf.

System.out.printf("%.2f",d);
yamafontes
  • 5,552
  • 1
  • 18
  • 18
0

In java, as in other languages, there is the issue of converting a decimal number into binary. It's not perfect, and it often results in rounding errors such as this. You should round the number or use integers where possible.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
  • http://en.wikipedia.org/wiki/IEEE_floating_point this is a good link if you want more information. I think someone else has already posted it though. – Anubian Noob Nov 22 '13 at 03:11
0

I'm not sure if you want the reason why that happen or what you can do for solve it. Well, anyway the reason is already answered, if you want to make it look like 1500.49, just do this print:

System.out.printf("%.2f",d);
João Silva
  • 531
  • 4
  • 21
  • 40
0

Looks like you are performing monetary calculations.

If that is the case, repeat with me: never use float nor double for such calculations.

If you need to perform monetary calculations on currencies with decimals (the vast majority of them) , use BigDecimal

Juan Antonio Gomez Moriano
  • 13,103
  • 10
  • 47
  • 65