Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected output in javascript when converting string to number

In MDN in this example on parseInt method

console.log(parseInt(4.7 * 1e22, 10)); // Very large number becomes 4
console.log(parseInt(4.7 * 1e20, 10)); //result is 470000000000000000000

or small number than 20 it give me expected result what is reason for this ?

like image 760
ahmed khattab Avatar asked Apr 08 '26 12:04

ahmed khattab


1 Answers

With help from @Xufox

console.log(parseInt(4.7 * 1e22, 10)); // Very large number becomes 4
console.log(parseInt(4.7 * 1e20, 10)); //result is 470000000000000000000

What's happening here in steps:

  • Calculation is done (4.7 * 1e20) and (4.7 * 1e22)
  • Result of calculation is stringified by the JavaScript engine so it can be passed to parseInt
  • The string is parsed back to a number
  • Finally it's logged

JavaScript truncates every number with more than 20 digits using the scientific notation. That means the result of the calculations are:

  • 470000000000000000000
  • 4.7e22

These are stringified before being passed to parseInt:

  • "470000000000000000000"
  • "4.7e22"

These are strings, not numbers. parseInt will now ignore everything after the dot in the second value and return 4.

like image 70
shotor Avatar answered Apr 11 '26 01:04

shotor