Unexpected output in javascript when converting string to number
On MDN into this example by 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 a small number than 20 that gives me the expected result, what is causing this?
source to share
With @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 performed (4.7 * 1e20) and (4.7 * 1e22)
- The result of the calculation
stringified
using the JavaScript engine, so it can be passed toparseInt
- The string is parsed for a number
- Finally, he ran
JavaScript truncates every number with more than 20 digits using scientific notation. This means that the results of the calculations are:
- 470000000000000000000
- 4.7e22
They are built prior to transfer to parseInt
:
- "470000000000000000000"
- "4.7e22"
They are strings, not numbers. parseInt
now ignores everything after the dot in the second value and returns 4
.
source to share
It doesn't work after a 20 digit integer with radix 10.
You can take a look at the description parseInt
:
Since some numbers include e in their string representation (for example ), using parseInt to truncate numeric values ββwill lead to unexpected results when used on very large or very small numbers. should not be used as a substitute .
6.022e23
parseInt
Math.floor()
From ECMA standard 252 V 5.1 15.1.2.2 parseInt (string, radius)
Step 13:
Let mathInt be a mathematical integer value that is represented by Z in radix-R notation, using the letters AZ and az for digits with values ββfrom 10 to 35. (However, if R is 10 and Z contains more than 20 significant digits, each significant digit after The 20th may be replaced by the digit 0 of the implementation's choice, and if R is not 2, 4, 8, 10, 16, or 32, then mathInt may be an implementation-dependent approximation to the mathematical integer value represented by Z in radix-R notation. )
...
Note
parseInt
can only interpret the leading part of a string as an integer value; it ignores any characters that cannot be interpreted as being part of an integer notation, and it does not indicate that any such characters were ignored.
var x = 5.7 * 1e20;
console.log(x);
console.log(parseInt(x, 10));
x = 5.7 * 1e21;
console.log(x);
console.log(parseInt(x, 10));
source to share