Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS number function adds up zeros at the end [duplicate]

Tags:

javascript

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?

like image 395
Alex Avatar asked Jul 20 '17 11:07

Alex


2 Answers

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')))
like image 193
Sankar Avatar answered Oct 04 '22 02:10

Sankar


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
like image 39
user2314737 Avatar answered Oct 04 '22 03:10

user2314737