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

fix bug json #140

Closed
why168 opened this issue Nov 21, 2019 · 1 comment
Closed

fix bug json #140

why168 opened this issue Nov 21, 2019 · 1 comment

Comments

@why168
Copy link

why168 commented Nov 21, 2019

-> % echo '{"id":1234567890123456789012,"name":"edwin"}' | json
{
  "id": 1.2345678901234568e+21,
  "name": "edwin"
}

why?
1234567890123456789012 -> 1.2345678901234568e+21

var VERSION = '9.0.6';

@trentm
Copy link
Owner

trentm commented Aug 28, 2020

Working with integers greater than 2**53 -1 is fraught. JS has a Number.MAX_SAFE_INTEGER above which precision is lost.

> 1234567890123456789012 > Number.MAX_SAFE_INTEGER
true

At or above 1e21, JS represents numbers with scientific notation:

> 1e20
100000000000000000000
> 1e21
1e+21

If you need to keep precision for integers above MAX_SAFE_INTEGER, you should use BigInt if you can. Unfortunately, BigInt doesn't serialize to JSON:

> obj = {"id":1234567890123456789012n,"name":"edwin"}
{ id: 1234567890123456789012n, name: 'edwin' }
> JSON.stringify(obj)
Thrown:
TypeError: Do not know how to serialize a BigInt
    at JSON.stringify (<anonymous>)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#Use_within_JSON

@trentm trentm closed this as completed Aug 28, 2020
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

2 participants