Arithmetic with double

From CodeCodex

Revision as of 02:08, 7 January 2012 by Nostromo (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)



You may find that

 System.out.println( 1.33 - 1.3 );
// output :  0.030000000000000027

The unexpected result is coming from the fact that internal floating-point number representation is not well suited for that kind of operation. The easiest way to solve this limitation is to the BigDecimal class :

 import java.math.BigDecimal;
   (new BigDecimal("1.33").subtract(new BigDecimal("1.3")));