Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a double to an int in Javascript without rounding

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.

like image 276
Rory Harvey Avatar asked Dec 05 '11 16:12

Rory Harvey


People also ask

How can I convert double to int in JavaScript?

Use parseInt() function to convert double to int in JavaScript. The parseInt() function parses a string argument and returns an integer of the specified radix.

Does double to int round down?

That is, the answer is always rounding down.

How do you convert a number to an integer in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.


2 Answers

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 
like image 165
kubetz Avatar answered Oct 11 '22 07:10

kubetz


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; 
like image 21
Pointy Avatar answered Oct 11 '22 07:10

Pointy