4

I have a weird problem with datatype:double.

Here is my code:

public class Example {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        double a = 1.0;
        for(int i =0; i<10;i++){
            System.out.println("Number => " + a );
            a += 0.1;
        }
    }

}

Output should be :

Number => 1.0
Number => 1.1
Number => 1.2
Number => 1.3
Number => 1.4
Number => 1.5
Number => 1.6
Number => 1.7
Number => 1.8
Number => 1.9

But, this code sample's result is :

Number => 1.0
Number => 1.1
Number => 1.2000000000000002
Number => 1.3000000000000003
Number => 1.4000000000000004
Number => 1.5000000000000004
Number => 1.6000000000000005
Number => 1.7000000000000006
Number => 1.8000000000000007
Number => 1.9000000000000008

I use eclipse to compile this code block. I tried it on netbeans but nothing changed.

How should it be happen ? Any ideas?

Regards

alicanbatur
  • 2,172
  • 1
  • 28
  • 36
  • 2
    That's just a problem of precision. – Sotirios Delimanolis May 30 '13 at 14:13
  • 4
    If exact representation of short decimal fractions matters to you, you should be using BigDecimal, not double. Double is based on binary fractions, and gives no special importance to ten or its powers. It is a more general way of storing and manipulating a useful approximation to a wide range of numbers. – Patricia Shanahan May 30 '13 at 14:18
  • I am looking for this for a long time. Almost everyone say that bigDecimal is the solution. But i just wonder why it happens like this. Btw, my que is dup, i did not noticed the other question. – alicanbatur May 30 '13 at 14:21

2 Answers2

1

It's not so easy. I would use Commons-Math

for (int i = 0; i < 10; i++) {
    a = Precision.round(a, 1);   // <- round to 1 digit after decimal point
    ...

I think the only Java SE alternative to that is

a = Double.parseDouble(String.format(Locale.US, "%.1f", a));
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

According to the javadoc

If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).

Here is the Source

MaheshVarma
  • 2,081
  • 7
  • 35
  • 58