Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toJSON: default value digits=4 is dangerous (can truncate data) #443

Open
simon-anders opened this issue Sep 7, 2024 · 0 comments
Open

Comments

@simon-anders
Copy link

The default parameter digits=4 can cause quite unexpected behaviour.

In the following example, we lose 2e-5, which is made zero, while both the larger and smaller numbers stay intact.

> jsonlite::toJSON( c( 2e-7, 2e-6, 2e-5, 2e-4, 2e-3 ) )
[2e-07,2e-06,0,0.0002,0.002] 

This here is also maybe not what one would expect:

> jsonlite::toJSON( (1:9)*1e-5 )
[1e-05,0,0,0,0,0.0001,0.0001,0.0001,0.0001] 

The issue arises because the smallest number representable in plain notation with 4 digits is 1e-4, but scientific notation (i.e., the one with e) is used only below 2e-5.

I would suggest setting the default value for digits to at least 5, or enforce that scientific notation is used as soon as the number is below 10^-digits

Curiously, by the way, the problem does not arise here:

> jsonlite::toJSON(10^(-6:0))
[1e-06,1e-05,0.0001,0.001,0.01,0.1,1] 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant