Converting a double to an int in Javascript without rounding

RSH1 picture RSH1 · Dec 5, 2011 · Viewed 148.8k times · Source

In C# the following code returns 2:

double d = 2.9;
int i = (int)d;
Debug.WriteLine(i);

In Javascript, however, the only way of converting a "double" to an "int" that I'm aware of is by using Math.round/floor/toFixed etc. Is there a way of converting to an int in Javascript without rounding? I'm aware of the performance implications of Number() so I'd rather avoid converting it to a string if at all possible.

Answer

kubetz picture kubetz · Dec 5, 2011

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