-1

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?

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
saltandwater
  • 791
  • 2
  • 9
  • 25
  • What do these numbers represent? Let's say they represent the amount of gin you need to use to make a cocktail. Does it really matter if you add a millionth of a billionth of liter more than needed? – JB Nizet Aug 22 '15 at 09:05
  • IMHO This is not a duplicate as the OP specifically states they are aware of the alternative of using BigDecimal. – Peter Lawrey Aug 22 '15 at 09:16

1 Answers1

0

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130