I have a problem where 20 character string converted the JS new NUMBER method.
var x4 = "22222222222222222222";
var x5 = "22222222222222222229";
Number(x4)
parseInt(x5);
//Output
22222222222222220000
22222222222222220000
I was expecting to get the same value as the variable but in number format but I dont know whats wrong here. What is the best way to convert string to number will any number of digits.
JavaScript stores numbers as Float64
(AKA IEEE 754 double-precision).
The way an integer (full number, no fraction) is thus limited to 53 bits (52 explicit and 1 implicit).
Any number larger than that cannot be stored without losing precision; a compromise is being made and an approximation is stored instead.
In JS you can get this number (2 ^ 53 - 1) using Number.MAX_SAFE_INTEGER
,
or if you'd like to check whether a number is a "safe integer" (No precision lost), Number.isSafeInteger
.
There is no way to store numbers larger than Number.MAX_SAFE_INTEGER
natively in JS; However, depending on the task you have at hand, a larger number can be (costly) emulated using a String
/Array
/Buffer
with custom methods for performing mathematical operations, using a third-party library which does it for you, or, if you're using NodeJS
, using a more efficient native (compiled) library for large numbers (Such as bignum).
Update:
Since I posted the above answer, JavaScript has gained support for BigInt, which is an arbitrarily-large safe integer format.
BigInt literals have also been added, which are just number with an n
suffix. So for your example:
const x4 = 22222222222222222222n;
const x5 = 22222222222222222229n;
no loss of precision here. You can even go further; The following will work without losing precision at all, albeit very slowly:
const veryLargeNumber = x4 ** 10000n;
// 29368033185714599045483110729334710018527698466665246504292741901594849999445152112231214493149844001358430994081988271893728711217783149614681323681876825053646556106638954761114573427277415424n