RSS Feed for This PostCurrent Article

Java: Trap in Arithmetic II

What will you expect from the following code?

   1: public static void main(String[] args) {
   2:     System.out.println(10.00-9.10) ;
   3:  
   4: }

Instead of printing “0.90”, it prints “0.9000000000000004” on my machine.

This is a know floating point issue with all languages. To get it correctly done in Java, you need to use BigDecimal class, passing the number as string.

   1: public static void main(String[] args) {
   2:    System.out.println(new BigDecimal("10.00").subtract(new BigDecimal("9.10"))) ;
   3:  
   4: }

For currency calculation, always use BigDecimal.


Trackback URL


Sorry, comments for this entry are closed at this time.