When I add float numbers using java it add extra fractions how to avoid them?

java

Solution

This has to do with the fact that many numbers that look simple in decimal notation cannot be represented exactly as binary floating-point numbers.

Let's examine the very first number in your example, `3.96`. When you store it in a `float`, it becomes `3.95999999999999996447`. This gets rounded when printed, so you don't see the error unless you print the number to many significant digits.

Thus the problem isn't so much to do with the addition, but with the numbers themselves. However, the errors accumulate as you add things up.

If you want your computations to be exact, you could use `BigDecimal` instead of `float`/`double`.

Problem

I am trying to add a long list of numbers that I defined as float. the numbers are shown blew, as illustrated while it is adding numbers it add some extra fractions, how to avoid those ? which data type should I use? ``` float number; float sum; ....{ ........ System.out.println(number); sum = sum + number; System.out.println("sum:" + sum); } ``` results ``` 3.96 sum:3.96 5.04 sum:9.0 5.04 sum:14.04 2.16 sum:16.2 1.44 sum:17.640001 3.96 sum:21.600002 3.96 sum:25.560001 2.88 sum:28.440002 10.26 sum:38.700005 1.62 sum:40.320004 3.01 sum:43.33 1.8 sum:45.13 1.98 sum:47.11 1.935 sum:49.045002 3.96 sum:53.005 1.44 sum:54.445 1.44 sum:55.885 1.44 sum:57.324997 6.48 sum:63.804996 4.3 sum:68.104996 ```

Original source