3

I run the following code, but did not expect that result..

public class SampleDemo {
    public static void main(String args[]) {  
        System.out.println(10.00 - 9.10);
    }
}

I am getting o/p as 0.9000000000000004

Why is it so?

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
evan
  • 41
  • 2
  • 1
    Read all those Related questions on the side there ---> http://stackoverflow.com/questions/5076710/what-is-float-in-java – Java Drinker May 20 '11 at 17:17
  • 5
    [Welcome to floating point arithmetic.](http://programmers.stackexchange.com/questions/62948/what-can-be-done-to-programming-languages-to-avoid-floating-point-pitfalls) :) – Adam Paynter May 20 '11 at 17:18

1 Answers1

6

This is because decimal values can’t be represented exactly by float or double.

One suggestion : Avoid float and double where exact answers are required. Use BigDecimal, int, or long instead


Using int :

public class SampleDemo {
    public static void main(String args[]) {  
        System.out.println(10 - 9);
    }
}

// Output : 1

Using BigDecimal :

import java.math.BigDecimal;

public class SampleDemo {
  public static void main(String args[]) {
     System.out.println(new BigDecimal("10.00").subtract(new BigDecimal("9.10")));
                             }
                     }
// Output : 0.90
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
  • 4
    Just to point out, if you need this kind of precision, go for [BigDecimal](http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html), which gives you more control over precision, scale, rounding politics, etc. – Anthony Accioly May 20 '11 at 17:18
  • Yes, @Anthony +1 I added it to my answer. :) – Saurabh Gokhale May 20 '11 at 17:21