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 compatibl
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
).
Using bitwise operators. It may not be the clearest way of converting to an integer, but it works on any kind of datatype.
Suppose your function takes an argument value
, and the function works in such a way that value
must always be an integer (and 0 is accepted). Then any of the following will assign value
as an integer:
value = ~~(value)
value = value | 0;
value = value & 0xFF; // one byte; use this if you want to limit the integer to
// a predefined number of bits/bytes
The best part is that this works with strings (what you might get from a text input, etc) that are numbers ~~("123.45") === 123
. Any non numeric values result in 0
, ie,
~~(undefined) === 0
~~(NaN) === 0
~~("ABC") === 0
It does work with hexadecimal numbers as strings (with a 0x
prefix)
~~("0xAF") === 175
There is some type coercion involved, I suppose. I'll do some performance tests to compare these to parseInt()
and Math.floor()
, but I like having the extra convenience of no Errors
being thrown and getting a 0
for non-numbers
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).
So I made a benchmark, on Chrome
when the input is already a number, the fastest would be ~~num
and num|0
, half speed: Math.floor
, and the slowest would be parseInt
see here
EDIT: it seems there are already another person who made rounding benchmark (more result) and additional ways: num>>0
(as fast as |0
) and num - num%1
(sometimes fast)
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
But the Wayback Machine saves the day! http://web.archive.org/web/20100422040551/http://james.padolsey.com/javascript/double-bitwise-not/
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"