views:

2182

answers:

9

There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice?

Here are a few methods that I know of:

var a = 2.5;
window.parseInt(a); // 2
Math.floor(a);      // 2
a | 0;              // 2

I'm sure there are others out there. Suggestions?

A: 

parseInt() is probably the best one. a | 0 doesn't do what you really want (it just assigns 0 if a is an undefined or null value, which means an empty object or array passes the test), and Math.floor works by some type trickery (it basically calls parseInt() in the background).

Jeff Hubbard
Are you sure you don't mean a || 0? A single | is a bitwise OR operator as far as I know, as opposed to the boolean OR operator. I'm not sure why it works, but try it in Firebug.
Mathew Byrne
Yes, this is a bitwise operation.
Jason Bunting
Also, where do you get your information about how Math.floor works?
Jason Bunting
You're right, `a||0` is logical or. That means that `a|0` is working in the exact same manner as Math.floor. My info about Math.floor comes from digging into the internals of spidermonkey for various personal projects.
Jeff Hubbard
Oh, okay - so for that implementation, that is how Math.floor works, not necessarily every implementation.
Jason Bunting
+3  A: 

You can use Number(a).toFixed(0);

Or even just a.toFixed(0);

Edit:

That's rounding to 0 places, slightly different than truncating, and as someone else suggested, toFixed returns a string, not a raw integer. Useful for display purposes.

var num = 2.7;  // typeof num is "Number"
num.toFixed(0) == "3"
davenpcj
FYI: The Number constructor runs very slow, so you wouldn't want to use that one if performance was important.
Jason Bunting
Good to know! I edited to add the 2nd a.toFixed(0); form when I remembered javascript primitives still have functions.
davenpcj
Well, to be honest...they don't have methods. The interpreter first converts the primitive to a Number object, and then calls the method on it. This simply happens invisibly for you. So, your second example implicitly does the same as the first. :(
Jason Bunting
Not only that, but if a is 2.5, a.toFixed(0) rounds it up to 3.
Jason Bunting
That's by design. http://www.w3schools.com/jsref/jsref_tofixed.asp, but I'll edit to reflect that.
davenpcj
+17  A: 

According to this website:

parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number...

For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable...

Jason Bunting
+2  A: 
var i = parseInt(n, 10);

If you don't specify a radix values like '010' will be treated as octal (and so the result will be 8 not 10).

wrumsby
Oh wow! Good to know ;)
Mathew Byrne
>>> parseInt(2e20)200000000000000000000>>> parseInt(2e21)2
Andrew B.
+2  A: 

To everyone suggesting parseInt: read the original post again, carefully. a is a numeric variable, not a string.

Thomas
A: 

The question appears to be asking specifically about converting from a float to an int. My understanding is that the way to do this is to use toFixed. So...

var myFloat = 2.5;
var myInt = myFloat.toFixed(0);

Does anyone know if Math.floor() is more or less performant than Number.toFixed()?

Andrew Hedges
+2  A: 

The answer has already been given but just to be clear.

Use the Math library for this. round, ceil or floor functions.

parseInt is for converting a string to an int which is not what is needed here

toFixed is for converting a float to a string also not what is needed here

Since the Math functions will not be doing any conversions to or from a string it will be faster than any of the other choices which are wrong anyway.

AnthonyWJones
A: 

you could also do it this way:

var string = '1';
var integer = a * 1;
first, you have a typo ("a" should be "string"), and second, that just converts a string to a number, not an integer. Try changing the string to '1.1'.
Jason S
+1  A: 

Apparently double bitwise-not is the fastest way to floor a number:

var x = 2.5;
console.log(~~x); // 2

Used to be an article here, getting a 404 now though: http://james.padolsey.com/javascript/double-bitwise-not/

Google has it cached: http://74.125.155.132/search?q=cache:wpZnhsbJGt0J:james.padolsey.com/javascript/double-bitwise-not/+double+bitwise+not&cd=1&hl=en&ct=clnk&gl=us

bcherry