Why does this output 0.6000000000000001 ? :confused:Code:`public void test () {`

double a = 0.2, b = 3;

System.out.println(a*b);

}

I need it to output 0.6

Printable View

- 03-25-2010, 09:41 PMGPBdouble a * double b = weird outputCode:
`public void test () {`

double a = 0.2, b = 3;

System.out.println(a*b);

}

I need it to output 0.6 - 03-25-2010, 09:50 PMJosAH
Imagine the following 'game': you have the numbers 1/2, 1/4, 1/8 ... 1/2^52. Given an arbitrary number d select the numbers (at most once) and add their values and try to make that sum equal to d; if you want you can multiply or divide your sum by two as many times as you want. That's how IEEE754 floating point numbers work. You can't make the number 0.2 with that 'game'.

An analogy in decimal: you can't make the number 1/3 given a finit number of decimals. That's why you get that 'funny' result. The cure: for representations of those floating point numbers that 'look better' have a look at the DecimalFormat class.

kind regards,

Jos - 03-26-2010, 10:32 AMTolls
And if you need accurate decimal representations (say for finance stuff) use BigDecimal.

- 03-26-2010, 11:40 AMDarrylBurke
Recommended reading:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

db