javascripttostringparseint

Does JavaScript Number.toString method lose accuracy after a threshold?


The output of the following:

let x = 10**23;
console.log(x.toString(16))

comes out 152d02c7e14af6000000 which actually computes to 99999999999999991611392 and not 10**23. Interestingly enough, the following doesn't compute to false:

let x = 10**23;
console.log(x==parseInt(x.toString(16),16))

Am I getting something wrong here?


Solution

  • JavaScript numbers are floating point, which lose precision the larger they get. When you exceed Number.MAX_SAFE_INTEGER (which is 253 – 1), the precision becomes >1.

    This also means that things like 10**23 === (1**23 - 123) evaluates to true.