Javascript convert Double to Integer

To convert a double to an integer in Javascript, you need to strip of the decimal part of the number. (That is equal to making it and integer – no type cast is necessary or possible)

You can do this by using any of the Math rounding functions:

var doubleNumber = 1.5;
var roundedNumber = Math.round(doubleNumber); // will be nearest integer (2)
var flooredNumber = Math.floor(doubleNumber); // will be 1
var ceiledNumber = Math.ceil(doubleNumber); // will be 2

Although a math rounding function isn’t explicitly guaranteed to return an int (like in .NET, Math.Floor(double d) returns double), this works regardless, because – in Javascript – all numbers without decimals are integers.

In other words, it’s impossible to have a double of value 1.0 (even 1.1 - 0.1 returns an integer 1).

A more explicit conversion can be achieved by using the following code:

var decimalNumber = 1.5;
var integerNumber = parseInt(decimalNumber);

Although harder to read, you may also use the following code:

var integerNumber = decimalNumber | 0;

The latter solution is credit to Merlyn, who has some very wierd javascript operation experiments on his website.