# How Computer deal with Floating point numbers

There are instances where computer can go wrong just like humans. After all it was humans who invented computers. A quite popular one of these problem s is the floating-point error.

Computer does every calculation in binary as it is its language. Although quite easy for us humans, even adding two simple numbers like 5+2 will be done in binary.

5 will be converted to 101

2 will be converted to 10

and the addition will be 111. Which will convert back to 7.

However, handling floating-point values is a bit complicated as they are handled using the IEEE-754 standard (which uses 32 bit single precision to represent floats and 64 bits to represent double values.

There are 3 main components in this IEEE-754 number for both the types.

**Mantissa –**0 represents a positive,1 represents a negative**The Biased exponent –**A bias is added to the actual exponent in order to get the stored exponent.**The Normalized Mantissa –**The part of a number in scientific notation or a floating-point number, consisting of its significant digits. Either 0 or1. So a normalized mantissa is one with only one 1 to the left of the decimal.

So 8.1 will be converted (in scientific notation)

8.0- 1.0000001100110011001100* ²³

8 binary value — 1000

0.1 binary value — 0001100110011001100…

8.1–1000.0001100110011001100…

# BigDecimal in Java

We can solve this problem using the java BigDecimal class. Java BidDecimal class provides operations for arithmetic, comparison, hashing, rounding, manipulation, and format conversion.

for the arithmetic operation, it provide add(), substract(), divide(), and multiply() methods.

public static void main(String[] args) {

for (BigDecimal i = BigDecimal.valueOf(100);

0 <= i.compareTo(BigDecimal.valueOf(0)); i =

i.subtract(BigDecimal.valueOf(.1))) {

System.out.println(i);

}

}

**References**