Reputation: 41
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?
Upvotes: 3
Views: 319
Reputation: 46395
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
Upvotes: 6