Converting a double to an int in Javascript without rounding
Solution 1:
Use parseInt()
.
var num = 2.9
console.log(parseInt(num, 10)); // 2
You can also use |
.
var num = 2.9
console.log(num | 0); // 2
Solution 2:
I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.
A trick that avoids a function call entirely is
var truncated = ~~number;
The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).
edit — In an update quite a while later, another alternative to the ~~
trick is to bitwise-OR the value with zero:
var truncated = number|0;
Solution 3:
Similar to C# casting to (int)
with just using standard lib:
Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1