Solving Floating point rounding error by using BigDecimal
BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. It can handle very large and very small floating point numbers with a great precision but compensating with the time complexity a bit. It gives user to full control over rounding behavior.
BigDecimal class has several constructors, for examples - BigDecimal(BigInteger val), BigDecimal(char[ ] in), BigDecimal(double val), BigDecimal(long val), BigDecimal(String val),etc
This class has several methods. Eg. add(), substract(), multiply(), divide(), etc.
Lets look at example.
Input : double a=0.03;
double b=0.04;
double c=b-a;
System.out.println(c);
Output :0.009999999999999998
Input : BigDecimal _a = new BigDecimal("0.03");
BigDecimal _b = new BigDecimal("0.04");
BigDecimal _c = _b.subtract(_a);
System.out.println(_c);
Output :0.01
If we are using BigDecimal(double val) constructor instead of String , we have to pass MathContext parameter to set the precision. i.e BigDecimal(double val, MathContext mc). This is how BigDecimal solves floating point rounding error.
Extract value from BigDecimal:
Eg. BigDecimal A = new BigDecimal("0.03");To get the double value => A.doubleValue();To get the string representation => A.toString();
Comparison:
if (a < b) {} // For primitive double
if (A.compareTo(B) < 0) {} // For BigDecimal
CompareTo() returns -1(less than), 0(Equal), 1(greater than).
Equality:
if (A.equals(B)) {} // A is equal to B
We have to use BigDecimal for formatting currency like critical operations. We can use float and double for simple calculations.
I hope you got an idea about BigDecimal.
Happy coding.