0

While I'm converting JSON String to JSON array the decimal part is getting rounded. On below example the value given is 33648.545 and the output is 33648.547. The library used is 'json-lib-2.4-jdk15.jar'. Can any one help to resolve the case.

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;

public class TestCode{

public static void main(String[] args){
  String jsonStr2 = "[{\"amount\":33648.545}]";
  JSONArray jArrayStr = (JSONArray) JSONSerializer.toJSON(jsonStr2);
  System.out.println(jArrayStr);
}
}
  • 1
    This might be a precision issue, i.e. if that number is parsed to a `float` the exact value cannot be represented. I don't know the library you're using so this is just a guess but try `System.out.println(33648.545f);` and you should see the same output, i.e. `33648.547`. – Thomas May 27 '21 at 06:28
  • @Thomas, yes, you are right. If I pass the value as, `String jsonStr2 = "[{\"amount\":33648.545d}]";` it will give correct output. i.e. 33648.545. Thank you. – Saheer Naduthodi May 27 '21 at 06:42
  • Changed the JSON parsing method from JSONUTIL to JACKSON to prevent BigDecimal false rounding and it worked. Used `ObjectMapper.readValue` – Saheer Naduthodi May 31 '21 at 05:39

0 Answers0