0

I am trying to do a relatively simple task of writing 1000000000000000000000 (as a number without quotes) to a json file using NodeJs. I have this number defined as a constant:

const NUM = 1000000000000000000000

If I simply write it, it comes out as 1e+21. Everything else I tried (big number...) ends up converting it to a string.

Can someone please help?

Update

To clarify what i am after, please look at the code below:

// 22 digits
const bigNum = 1000000000000000000000;
console.log(JSON.stringify(bigNum)); // Output: 1e+21

// 19 digits
const bigNum2 = 1000000000000000000;
console.log(JSON.stringify(bigNum2));  // Output: 1000000000000000000

What i would like is to be able to output 1000000000000000000000 in the first example instead of 1e+21

Nahu
  • 143
  • 10
  • Does this answer your question? [JSON integers: limit on size](https://stackoverflow.com/questions/13502398/json-integers-limit-on-size) – m90 Mar 11 '21 at 18:30

1 Answers1

0

If I simply write it, it comes out as 1e+21. Everything else I tried (big number...) ends up converting it to a string.

JSON will always be a string in its serialized representation. It also does not impose any limits on number sizes, although you might of course hit limits imposed by the runtime you use to serialize your data into JSON:

> let num = JSON.stringify(Number.MAX_SAFE_INTEGER + 1)
undefined
> JSON.parse(num)
9007199254740992
> Number.MAX_SAFE_INTEGER + 1
9007199254740992

The exponential notation does not change the value but just saves bytes and is easier to read:

> 1e+21 === 1000000000000000000000
true
m90
  • 11,434
  • 13
  • 62
  • 112
  • "*JSON will always be a string*" OP seems to just have regular code they call "JSON" when it isn't: `const NUM = 1000000000000000000000` – VLAZ Mar 11 '21 at 18:52
  • Hmm. Then how would the Number be converted to a String though? – m90 Mar 11 '21 at 19:22
  • Yes, it's a bit unclear. OP also mentions BigInt but that's not serialisable to JSON. I'm not totally sure *what* is happening. – VLAZ Mar 11 '21 at 19:26