javascriptnode.jstypescripttype-conversionparseint

Why does JavaScript's parseInt(0.0000005) print "5"?


I've read an article about JavaScript parseInt, which had this question:

parseInt(0.5);      // => 0
parseInt(0.05);     // => 0
parseInt(0.005);    // => 0
parseInt(0.0005);   // => 0
parseInt(0.00005);  // => 0
parseInt(0.000005); // => 0

parseInt(0.0000005); // => 5

Why is this happening?


Solution

  • Based on ecmascript standard:

    The parseInt function produces an integral Number dictated by interpretation of the contents of the string argument according to the specified radix.

    Part1 - Converting 0.0000005 to string:

    The first step of parseInt function is converting the input to string if it is not:

    19.2.5 parseInt ( string, radix )

    When the parseInt function is called, the following steps are taken:

    1. Let inputString be ? ToString(string).
    2. Let S be ! TrimString(inputString, start).

    ...

    In each case, the string output is as follows:

    String(0.5);      // => '0.5'
    String(0.05);     // => '0.05'
    String(0.005);    // => '0.005'
    String(0.0005);   // => '0.0005' 
    String(0.00005);  // => '0.00005'
    String(0.000005); // => '0.000005'
    
    String(0.0000005); // => '5e-7'
    

    Part2 - Converting 5e-7 to integer:

    So, it means when we use parseInt(0.0000005), it is equal to parseInt('5e-7') and based on the definition:

    parseInt may interpret only a leading portion of string as an integer value; it ignores any code units that cannot be interpreted as part of the notation of an integer, and no indication is given that any such code units were ignored.

    So the answer will return 5 only because it is the only character which is a number till a noncharacter e, so the rest of it e-7 will be discarded.

    Thanks to @jcalz, I should mention that:

    Don't use parseInt(x) for x that isn’t a string. If you already have a number presumably you want Math.round() or Math.floor() or something.