Search code examples
javascriptparseint

Clarification regarding parseInt() in Javascript


parseInt(0.000004); //0 
parseInt(0.0000004);  //4 

why does the first parseInt() return 0, but if I increase the number of zeros after decimal it gives 4?


Solution

  • It's partly because parseInt() expects a string for its argument and first converts anything else to a string.

    console.log(0.000004.toString());
    // "0.000004"
    
    console.log(0.0000004.toString());
    // "4e-7"
    

    And, parseInt() doesn't recognize e-notation and, in the latter case, accepts just the "4" from the resulting string.