One of the solutions to a floating-point error in java is Big decimal. We can define the BigDecimal as an arbitrary-precision signed immutable number. This BigDecimal has two parts namely,

1. Unscaled value — an arbitrary precision integer.

2. Scale — A 32-bit integer representing the number of digits to the right of the decimal point.

So as an example, we get the number 5.432, this has an unscaled value of 5432, and the scale value is 3.

BigDecimal is really helpful when you dealing with high-precision arithmetic operations. In below, I have added a sample code which is using addition, subtraction, multiplication and division.

Let’s get a real-world example. Try to run the below application on your machine.

This will endlessly as below.

To avoid this floating point error, as we discussed, we can use BigDecimal. Below, is the code that is used to avoid the floating-point error in java using BigDecimal.

Now the output will be as follow with exact values.

So this is all about how to solve the floating-point error using BigDecimals in java. Hope you enjoy the tutorial and see you in next tutorial.

Software Engineer