Why parseInt(0.0000005) returns 5: The dangerous interaction between scientific notation and string coercion.
This post explains a quiz originally shared as a LinkedIn poll.
🔹 The Question
What will be the output / behavior?
const value = 0.0000005;
const result = parseInt(value);
console.log(result);
Hint: parseInt converts its first argument to a string before parsing. How does JavaScript represent very small numbers as strings?
Follow me for JavaScript puzzles and weekly curations of developer talks & insights at Talk::Overflow: https://talkoverflow.substack.com/
🔹 Solution
The correct output is 5.
🧠 How this works
This behavior is a classic example of implicit type coercion combined with scientific notation.
- Implicit String Conversion: The
parseIntfunction expects its first argument to be a string. If you pass a number, JavaScript first converts it to a string using the abstractToStringoperation. - Scientific Notation: For very small numbers (specifically, those with more than 6 leading zeros after the decimal point), JavaScript's default string representation uses exponential notation.
-
String(0.000005)is"0.000005" -
String(0.0000005)is"5e-7"
-
- Parsing Logic:
parseIntparses the string from left to right. It stops parsing as soon as it encounters a character that is not a valid digit for the specified radix (default is 10).- It sees
"5"(valid digit). - It sees
"e"(invalid digit). - It stops and returns the integer parsed so far:
5.
- It sees
🔍 Line-by-line explanation
const value = 0.0000005;
// value is stored as a number
const result = parseInt(value);
// Step 1: value is coerced to string -> "5e-7"
// Step 2: parseInt("5e-7") starts parsing
// Step 3: Parses '5', stops at 'e'
// Result: 5
console.log(result); // Output: 5
🔹 Key Takeaways
-
parseIntis for strings. Avoid using it on values that are already numbers. - Know your string representations. JavaScript automatically switches to scientific notation for numbers smaller than
1e-6. - Use Math methods for numbers.
Math.trunc()is the safer, semantic equivalent for "drop the decimal part" on numeric values.
Top comments (0)