# double a * double b = weird output

• 03-25-2010, 09:41 PM
GPB
double a * double b = weird output
Code:

```    public void test () {         double a = 0.2, b = 3;         System.out.println(a*b);     }```
Why does this output 0.6000000000000001 ? :confused:
I need it to output 0.6
• 03-25-2010, 09:50 PM
JosAH
Quote:

Originally Posted by GPB
Code:

```    public void test () {         double a = 0.2, b = 3;         System.out.println(a*b);     }```
Why does this output 0.6000000000000001 ? :confused:
I need it to output 0.6

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 AM
Tolls
And if you need accurate decimal representations (say for finance stuff) use BigDecimal.
• 03-26-2010, 11:40 AM
DarrylBurke