views:

7057

answers:

4

I'd like to convert a float to an int in Javascript. Actually, I'd like to know how to do BOTH of the standard convertions: by truncating and by rounding. And efficiently, not via converting to a string and parsing.

+23  A: 
var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue ); 
var intvalue = Math.round( floatvalue );

Math object reference

moonshadow
+2  A: 

For truncate: var intvalue = Math.floor(value);

For round: var intvalue = Math.round(value);

Mike
stackoverflow is very unfreindly to slow types, nice answer anyway :-)
dpavlin
Thanks buddy. :) I was a few seconds off from moonshadow who gets all the credit! :p Guess you are right.
Mike
+2  A: 

Note: You cannot use Math.floor() as a replacement for truncate, because Math.floor(-3.1) = 4 and not 3!

A correct replacement for truncate would be:

function truncate(_value)
{
  if (_value<0) return Math.ceil(_value);
  else return Math.floor(_value);
}
Shyru
That depends on the desired behavior for negative numbers. Some uses need negative numbers to map to the more negative value (-3.5 -> -4) and some require them to map to the smaller integer (-3.5 -> -3). The former is normally called "floor". The word "truncate" is often used to describe either behavior. In my case, I was only going to feed it negative numbers. But this comment is a useful warning for those who DO care about negative number behavior.
mcherm
+2  A: 

In your case, when you want a string in the end (in order to insert commas), you can also just use the Number.toFixed() function, however, this will perform rounding.

Russell Leggett