How do you use double to get the expected result

74 views Asked by At

I was trying out subtracting numbers in java, and this gives me unexpected result

public class FloatWeird
{
    public static void main(String[] args)
    {
        double n = 1;

        for(int i = 0;i<10;i++)
        {
            System.out.println(n);
            n = n - 0.10;
        }

    }
}

Result

1.0
0.9
0.8
0.7000000000000001
0.6000000000000001
0.5000000000000001
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014

I have gone through a few forums and understand that using the BigDecimal class is one solution. However, is there a way to correct it in a simpler way using double as above?

1

There are 1 answers

0
Peter Lawrey On

I suggest you use appropriate rounding.

System.out.printf("%.1f%n", n);

When ever you print a double you have to consider what the appropriate round is.

You can also round the result as you calculate which is what BigDecimal does.

n = n - 0.10;
n = Math.round(n * 10) / 10.0;

This will reduce cumulative error.

Another approach is to work in a different unit, e.g. instead of dollar you use cents. This means you can use an int or long and only convert to dollars for presentation.

long n = 100;
for(int i = 0; i < 10; i++) {
    System.out.println(n / 100.0);
    n = n - 10;
}

this prints http://ideone.com/Uf70jC

1.0
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1

Note: even if you use BigDecimal, this still have to do this except the API can help you determine at what point you should do this.