rudolph-miller / jonathan

JSON encoder and decoder.
http://rudolph-miller.github.io/jonathan/overview.html
164 stars 24 forks source link

writing a float only uses two digets after the decimal #33

Closed tmccombs closed 8 years ago

tmccombs commented 8 years ago

If you encode a float with to-json, only two digits after the decimal are kept, and scientifc notation is never used for very large numbers. Ex:

(jonathan:to-lisp 0.33333334) => "0.33"
(jonathan:to-lisp 1e30) => "1000000000000000000000000000000.00"

I'm sure there was a good reason for doing this, since there was commit that just added a special %to-json implementation for floats that used (format nil "~$" number). But it is difficult to work around if you want more than 1/100th in accuracy in your json. And it is inconsistant with ratios:

(jonathan:to-lisp 1/3) => "0.33333334"

I don't know what the reason behind using "~$" to output the number was, but at the very least the number of digits should be configurable.

fukamachi commented 8 years ago

I found this issue too while encoding Latitude and Longitude, which are should be decimal.

(jojo:to-json 35.65910807942215d0)
;=> "35.66"

According to the document, ECMAScript's Number can represent double-precision floating-point, so rounding the Common Lisp values doesn't make sense. http://www.ecma-international.org/ecma-262/5.1/#sec-8.5

FYI, CL-JSON uses ~F format directive for encoding real values.

(cl-json:encode-json 35.65910807942215d0 nil)
;=> "35.65910807942215"

https://github.com/hankhero/cl-json/blob/6dfebb9540bfc3cc33582d0c03c9ec27cb913e79/src/encoder.lisp#L410-L422

rudolph-miller commented 8 years ago

Fixed via https://github.com/Rudolph-Miller/jonathan/commit/fba9d5e085cae92e7a565ffa2ec0699dcf723a30

Thanks! :octocat: