Search code examples
javascriptecmascript-5

Function parseInt (1/10000000) returns 1. Why?


Why parseInt(1/10000000) results 1, when parseInt(1/1000000) result is 0?

I need some analog to Java's int casting like int i = -1/10000000;, Which is 0.

Should I use Math.floor for positive and Math.ceil for negative? Or is there another solution?


Solution

  • At first the question seems interesting. Then I looked at what 1/10000000 is.

    < 1/10000000
    > 1e-7
    

    Therefore:

    < parseInt("1e-7"); // note `parseInt` takes a STRING argument
    > 1
    

    If you want to truncate to an integer, you can do this:

    function truncateToInteger(real) {
        return real - (real % 1);
    }