DEV Community

ValPetal Tech Labs
ValPetal Tech Labs

Posted on

Question of the Day #23 [Talk::Overflow]

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);
Enter fullscreen mode Exit fullscreen mode

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.

  1. Implicit String Conversion: The parseInt function expects its first argument to be a string. If you pass a number, JavaScript first converts it to a string using the abstract ToString operation.
  2. 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"
  3. Parsing Logic: parseInt parses 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.

🔍 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
Enter fullscreen mode Exit fullscreen mode

🔹 Key Takeaways

  • parseInt is 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)