Loss of precision for double values
Brought to you by:
aalmiray
In version 2.4 json-lib is losing precision when parsing double values. This problem is not present in 2.3 and appears to have been introduced by
Better support for parsing numbers - ID: 3123950
Code:
double pi = 3.14159265358;
String jsonString = "{\"pi\":" + pi + "}";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
System.out.println(pi);
System.out.println(jsonString);
System.out.println(jsonObject);
Output:
3.14159265358
{"pi":3.14159265358}
{"pi":3.1415927}
I can confirm this problem, it has forced me to revert upgrading to 2.4 and was a difficult and subtle issue to catch, as it was it was silently shortening the precision of geo coordinates we query from an external API from double to float, simply cutting of several decimal digits.
The problem is caused by JSONTokener.nextValue new usage of commons-lang's NumberUtils to convert strings to numbers. That utility class does first try to convert to a Float, which succeeds even if the number has more decimal digits.
This is an issue reported in commons-klang but it seems to will not be resolved soon: https://issues.apache.org/jira/browse/LANG-693
View and moderate all "bugs Discussion" comments posted by this user
Mark all as spam, and block user from posting to "Bugs"
Also confirming. This is not good especially because you can generate a JSON number with the usual precision, but attempting to re-read it back will truncate it. Since we use JSON in a financial setting, we cannot lose precision and had to revert to 2.3.
Hi,
the loss of precision of double values (caused by using NumberUtils.createNumber in net.sf.json.util.JSONTokener.nextValue()) forced me to go back to 2.3.
the most simple fix would imho be replacing
return NumberUtils.createNumber(s);
by
return new BigDecimal(s);
this will avoid loss of precision. I don't think there is any other sideeffect but need some more memory
greetings
Peter
This is major issue issue for us. We lose lots of precision.
Sounds like Peter's recommendation is good.
Can we get out a 2.4.1?
Yes, when I converting BigDecimal from JSONObject, I lose decimal precision in big data. It is big problem for 2.4 lib.
After that when I rollback to 2.3 it working fine!!!
Developer team should fix as soon as possible....
Same issue for a map app which needs lat/lon processing.
I was affected by this issue some time ago and I was forced to downgrade to json-lib 2.3. Is there any fix for this so that we don't have to downgrade?