Search code examples
javascriptarraysnumbersparseint

Conversion issue for a long string of integers in JavaScript


I'm trying to convert a long string which has only integers to numbers.

var strOne = '123456789123456789122';
parseInt(strOne, 10);
// => 123456789123456800000

var strTwo = '1234567891234567891232';
parseInt(strTwo, 10);
// => 1.234567891234568e+21

The expected output should be the same as strOne and strTwo but that isn't happening here. While converting the string to a number, the output gets changed.

What's the best way to fix this issue?


Solution

  • BigInt is now available in browsers.

    BigInt is a built-in object that provides a way to represent whole numbers larger than 253, which is the largest number JavaScript can reliably represent with the Number primitive.

    value The numeric value of the object being created. May be a string or an integer.

    var strOne = '123456789123456789122';
    
    var intOne = BigInt(strOne);
    
    var strTwo = '1234567891234567891232';
    
    var intTwo = BigInt(strTwo);
    
    console.log(intOne, intTwo);