Javascript is famous for its lack of preciseness, so it always surprises and make joke with the developers by breaking the common sense or instinct.
Javascript doesn’t provide integer
type, but in daily life, integer
sometimes is necessary, then how can we convert a trim a float number into integer in Javascript?
Some very common answers might be Math.floor
, Math.round
or even parseInt
. But besides calling Math functions, is there any other answer?
The answer is bitwise operations. Amazing? Yes. Because bitwise operations are usually only applied to integers, so Javascript will try to convert the number
into "integer"
internally when a bitwise operation is applied, even it is still represented in type of number
Suppose value = 3.1415926
, and we want integer
is the trimmed value of value
, then we can have:
|
|
For more detail information about bitwise operation in javascript, please check out the MDN document
All approaches listed before are working, but with different performance. And according to the result from JsPerf, I sort the algorithms by performance from good to bad:
integer = ~~value;
integer = value >>> 0;
andinteger = value << 0;
integer = Math.floor(value);
integer = value >> 0;
integer = value | 0;
integer = Math.round(value);
integer = parseInt(value);
NOTE: The test cases are running in Chrome 24.0.1312.57 on Mac OS X 10.8.2