# Convert string to number, does not work for a large number? [duplicate]

1

I have the following string to convert from string to number: 42092537170271621 and it does not convert me as such, see the results:

``````Number('42092537170271621') -> 4209253717027162
parseInt('42092537170271621')->42092537170271624
parseFloat('42092537170271621')->42092537170271624
``````

Why is this happening? Is it because of the limits of that method? And if so, how Could I solve it ?, I must convert and then add several values.

asked by joselo 17.10.2018 в 17:56
source

1

Your number is larger than the maximum safe number possible in Javascript, that means that numbers larger than that lose precision, that's due to the way that Javascipt has to represent the numbers ( Double precision floating point format below the comparison:

``````console.log(42092537170271621)
console.log(Number.MAX_SAFE_INTEGER)``````

If you need to operate with this number, you can do it either by reducing it in some way (depends on what you want to do) or doing the algorithm (a sum one division .. etc) yourself and treating each part of the number individually. Here an example of the division algorithm.

1

Example with the BitInteger library for numbers that exceed the capacity of int. For more info .

``````console.log("4209253717027162111");
console.log(parseInt("4209253717027162111"));
console.log(bigInt("4209253717027162111"));``````
``<script src="http://peterolson.github.com/BigInteger.js/BigInteger.min.js"></script>``

Since in ES6 the integers operate at 32 bits, the maximum size of an integer variable is `2,147,483,647` .