Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't convert string to number without losing precision in JS?

We all know that +, Number() and parseInt() can convert string to integer.
But in my case I have very weird result.
I need to convert string '6145390195186705543' to number.

let str = '6145390195186705543';
let number = +str; // 6145390195186705000, but should be: 6145390195186705543 

Could someone explain why and how to solve it?

like image 819
David RJ Avatar asked Aug 23 '18 11:08

David RJ


4 Answers

Your number is above the Number.MAX_SAFE_INTEGER (9,007,199,254,740,991), meaning js might have a problem to represent it well.

More information

like image 118
Programmer Avatar answered Sep 27 '22 23:09

Programmer


You are outside the maximum range. Check in your console by typing Number.MAX_SAFE_INTEGER

If you want a number outside this range, take a look into BigInt that allows to define numbers beyond the safe range

https://developers.google.com/web/updates/2018/05/bigint

Read the documentation well before using it since the usage is different than usual

like image 31
cdoshi Avatar answered Sep 27 '22 21:09

cdoshi


I am guessing this is to solve the plusOne problem in leetcode. As others have answered, you cannot store value higher than the max safe integer. However you can write logic to add values manually. If you want to add one to the number represented in the array, you can use the below function. If you need to add a different value, you need to tweak the solution a bit.

var plusOne = function(digits) {
    let n = digits.length, carry=0;
    if(digits[n-1]<9){
        digits[n-1] +=1;        
    } else{
        digits[n-1] = 0;
        carry=1;
        for(let i=n-2;i>=0;i--){
            if(digits[i]<9){
                digits[i]+=1;
                carry=0;
                break;
            }else{
                digits[i]=0;
            }
        }
        if(carry>0){
            digits.unshift(carry);
        }
    }
    return digits;  
};
like image 20
Kirushna Avatar answered Sep 27 '22 21:09

Kirushna


Short answer: Your string represents a number to large to fit into the JavaScript number container.

According to the javascript documentation the maximum safe number is 2^53 which is 9007199254740992 source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number When you try and convert your number you're creating an overflow exception so you get weird results.

like image 36
max meijer Avatar answered Sep 27 '22 23:09

max meijer