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 );
moonshadow
2009-02-27 20:21:02
+2
A:
For truncate: var intvalue = Math.floor(value);
For round: var intvalue = Math.round(value);
Mike
2009-02-27 20:22:47
stackoverflow is very unfreindly to slow types, nice answer anyway :-)
dpavlin
2010-05-20 20:26:57
Thanks buddy. :) I was a few seconds off from moonshadow who gets all the credit! :p Guess you are right.
Mike
2010-05-22 20:25:58
+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
2009-10-14 16:17:26
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
2009-10-16 14:35:21
+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
2009-10-14 16:30:48