javascriptstringnumbers

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?


Solution

  • 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