7

I am using the Number() JS function which is supposed to convert string value to numeric.

It's working fine for small numbers. For big ones - it is starting to substitude values with zeros as shown on the image:

enter image description here

Is there a work around for this problem?

Alex
  • 4,607
  • 9
  • 61
  • 99

2 Answers2

2

This is because you're using numbers that are larger than Number.MAX_SAFE_INTEGER and Javascript does not guarantee to represent these numbers correctly

Use Number.isSafeInteger to check:

> Number.isSafeInteger(Number('111111111111111111'))
< false
user2314737
  • 27,088
  • 20
  • 102
  • 114
2

In JS, the largest integral value is 9007199254740991 That is, all the positive and negative integers should not exceed the -9007199254740991 and 9007199254740991 respectively.

The same is defined as the 253-1.

console.log(Number.isSafeInteger(parseInt('1111111111')))
console.log(parseInt('1111111111'))
console.log(Number.isSafeInteger(parseInt('111111111111111111')))
console.log(parseInt('111111111111111111'))
//9007199254740991 - The largest JS Number
console.log(Number.isSafeInteger(parseInt('9007199254740991')))
Sankar
  • 6,908
  • 2
  • 30
  • 53