# Thread: double a * double b = weird output

1. Member
Join Date
Feb 2010
Posts
20
Rep Power
0

## double a * double b = weird output

Java 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

2. Originally Posted by GPB
Java 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

3. Moderator
Join Date
Apr 2009
Posts
11,302
Rep Power
18
And if you need accurate decimal representations (say for finance stuff) use BigDecimal.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•