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

5

7

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?

Whoa answered 23/8, 2018 at 11:8 Comment(0)
H
2

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

Highlight answered 23/8, 2018 at 11:17 Comment(0)
B
2

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

Ballyhoo answered 23/8, 2018 at 11:18 Comment(0)
S
2

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;  
};
Sterilize answered 5/5, 2019 at 0:30 Comment(0)
S
1

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.

Saturninasaturnine answered 23/8, 2018 at 11:23 Comment(0)
E
0

Now, you can use the BigInt to fix it.

BigInt values represent numeric values which are too large to be represented by the number primitive.

let str = `6145390195186705543`;
let number = BigInt(str);
// 6145390195186705543n

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

Easeful answered 4/6, 2024 at 7:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.