Floating Point Round Problems
It is really a common problem which the programmer faces during working with floating numbers. I’ll explain it by using following coding examples.
When we run this Java program it should supposed to provide Real Sum as Expected Sum. But, let’s see what this program will actually provide.
So, as you can see this example will actually provide output as above. As you can see it provides quietly different output than the expected output (That means real sum is not comply with actual sum).
This particular problem is known as Floating Point Problem.
The reason for the Floating Point Problem is because the machine can not convert all decimal fractions into its exact binary format.
We can avoid these problems we can use BigDecimal Class in Java.
Big Decimal allows you to store the numbers exactly you are trying to represent. Big Decimal comes with java.math package along with the Big Integer.
Big Integer theoretically deals with unlimited amount of digits which only limited by memory while Big Decimal theoretically deals with both integral and fractional parts of numbers.
As well, Big Decimal can have 2 constructors known as
i. BigDecimal (Double)
ii. BigDecimal (String)
It is better to use BigDecimal String constructor because double constructor again provides some inaccuracies due to it limits on 15–17 digits.
Let’s see how we can use BigDecimal class to avoid that Floating Point Round Problem.
First let’s create seperate java class file called “FloatingPointProblemCorrection” in same package. In this class I’ve created 2 distinctive objects from the Big Decimal class (called a and b) and assigned previously assigned value for them using String Constructor. In this time wanna import java math package also. You can see it below.
Then, as previously we should add these 2 variables. In here, we called add() as follows to get the real summation result. As well, we can create another object from Big Decimal class to assign expected results as shown below.
In order to get the show the results we can use below statements from this class.
Finally, let’s go back to main method to execute this program. In here, I’m slightly change the code by adding 2 statements to show differences between what will happen before and after using Big Decimal for your convenience.
Let’s run this file and see what will happen.
Now you can see what will happen for our results before and after using Big Decimal Class.
Hope you get a clear understanding about how can we avoid floating point round problem by using Big Decimal Class in Java.
Stay Safe !!!