#116 Loss of precision for double values

open
nobody
None
5
2015-01-09
2011-02-15
Anonymous
No

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}

Discussion

  • Lasse

    Lasse - 2011-11-09

    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

     
  • Comment has been marked as spam. 
    Undo

    You can see all pending comments posted by this user  here

    Anonymous - 2012-06-05

    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.

     
  • peter plumber

    peter plumber - 2012-08-05

    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

     
  • billnbell

    billnbell - 2013-09-24

    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?

     
  • Surendra Jnawali

    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....

     
  • Jeff Black

    Jeff Black - 2015-01-09

    Same issue for a map app which needs lat/lon processing.

     

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks