Sunday, February 8, 2015

How to use BigDecimal to add or subtract float and double in Java

How to use BigDecimal to add or subtract float and double in Java
-------------------------------------------------------------------
How to make precision calculations correct with floats or doubles?

If you try this:

 Select

. System.out println ( 1 . 3 - 1 . 2 );
You get: 0.10000000000000009 instead of 0.1, as shown on your calculator. In fact, it is impossible to accurately represent 0.1 or any negative power of 10 using a float or a double. The best solution for this problem is to use the java.math.BigDecimal class. For example, it is used like this:

 Select
BigDecimal bd1 =  new  BigDecimal ( " 1.3 " );
BigDecimal bd2 =  new  BigDecimal ( " 1.2 " );
. System.out println (bd1. substract (bd2));
Please note, you want to represent numbers must be passed as Strings in the constructor

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.