json-bigint icon indicating copy to clipboard operation
json-bigint copied to clipboard

Long decimals

Open brettlangdon opened this issue 9 years ago • 4 comments

There are cases where a decimal with a lot of decimal places is converted to a BigNumber when it doesn't have to be:

> JSON.parse('3.6666666666666665')
3.6666666666666665
> JSONBig.parse('3.6666666666666665')
{ s: 1,
  e: 0,
  c:
   [ 3,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     6,
     5 ] }

This is caused by the check for a number longer than 15 characters in length. From some mild investigation, it seems like the max length for decimals is 18 characters not 15.

Not sure if the right approach is to just change this check https://github.com/sidorares/json-bigint/blob/919bdb9085dc209d20f5dc38c005079ff39e6db8/lib/parse.js#L172 to something like:

if ((string.indexOf('.') > 0 && string.length > 18) || string.length > 15)

This issue was brought up in brettlangdon/node-dogapi#16

brettlangdon avatar Aug 06 '15 23:08 brettlangdon

we have ( possibly not precise ) number here - https://github.com/sidorares/json-bigint/blob/919bdb9085dc209d20f5dc38c005079ff39e6db8/lib/parse.js#L164

Maybe add check "if bignumber .toString() id same as number.toString() - it's safe to return a number?"

sidorares avatar Aug 07 '15 00:08 sidorares

That means that sometimes numbers outside of safe intereg precision will e returned as JS numbers, for example 9007199254740994 would be returned as number but 9007199254740995 - as Bignumber

sidorares avatar Aug 07 '15 00:08 sidorares

Yeah, it might just be safer to prefer to convert numbers to BigNumber. However, it might catch people off guard who are not expecting a BigNumber.

> var num = new BigNumber(5);
undefined
> num
{ s: 1, e: 0, c: [ 5 ] }
> num + 5
'55'

brettlangdon avatar Aug 07 '15 00:08 brettlangdon

why not add to options the option to remain number if able to?

lilling avatar Sep 18 '17 13:09 lilling