3

I am running weird situation. I am counting the numbers using Double parseDouble. In some situation i am getting extra 0's for instance instead of 109.1 i am getting ... 109.10000001.

I am trying to add string from json.

Here is the line of code I am executing.

points = points + Double.parseDouble(x.points);
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
dhiku
  • 1,818
  • 2
  • 22
  • 38

3 Answers3

4

Java uses IEEE floating point numbers for its double (and float) datatypes. A double has a lot of precision, but not infinite precision. Some numbers are only approximated.

In addition (no pun intended), adding numbers like this together compounds the floating point errors. Eventually the error is large enough to notice, such as with your issue here.

If you can accept a performance hit, then use BigDecimal, which is arbitrary precision.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

It is probably unrelated to the Double.parseDouble, but rather a floating-point precision issue. Floats and doubles are encoded in binary as a mantissa and an exponent. The part after the decimal point is a particular problem because what can be represented easily in base 10 cannot necessarily be represented well in base 2. For example, the decimal number 0.2 becomes infinitely repeating in binary, rather like 1/3 in decimal (0.333...). I suggest rounding to a fixed number of digits for display, or perhaps using java.math.BigDecimal instead.

David Cummins
  • 972
  • 6
  • 15
0

This actually has a very complicated answer, but essentially floating point numbers are often only approximations of the number you give it.

A good example from wikipedia is 0.1, which in floating point is 0.009999999776482582092285156250.

greedybuddha
  • 7,488
  • 3
  • 36
  • 50