Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java long values rounded off in json response

Tags:

java

json

While getting a JSON response from my restful service implemented in JAVA, I am observing that the long data type values ending with 01 are rounded off to 00. For example:

the long values,

12345123459876501 is returned as 12345123459876500 (last digit rounded to 0)

12345123459876502 is returned as 12345123459876502

12345123451234501 is returned as 12345123451234500 (last digit rounded to 0)

12345123451234502 is returned as 12345123451234502

Could anybody help me understand why only the values ending with 01 are getting rounded to 00?

like image 356
BalajiBabu Avatar asked Apr 09 '14 16:04

BalajiBabu


1 Answers

JSON as defined at json.org has just a single numeric type called "number". So many JSON parsers for Java will map that to double type regardless of whether it is used for integer, long, of floating-point numbers. However, a double can only hold 15-16 significant digits while a long can store more. So if you have a long value with more digits than that, precision is lost when the JSON parser converts between long and double, which changes your 01 suffix to 00. If you want to be sure all digits are preserved, you must change your field type to String and handle parsing to long by yourself.

like image 124
Michał Kosmulski Avatar answered Sep 28 '22 01:09

Michał Kosmulski