Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double parseDouble adding extra 0's when adding the numbers

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);
like image 282
dhiku Avatar asked Jan 28 '26 19:01

dhiku


2 Answers

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.

like image 52
rgettman Avatar answered Jan 30 '26 10:01

rgettman


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.

like image 22
David Cummins Avatar answered Jan 30 '26 10:01

David Cummins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!