Last year, a colleague asked me how to convert decimals into integers (minus decimal places) in JavaScript, when I answered parseint directly. In fact, there was no other way to think about the problem. But recently, while looking at someone else's it code, I found him writing code like this.
var random = (Math.random () * 2) | 0; Get random 0 or 1
we all know that the number of JavaScript is actually double-precision floating-point numbers, and Math.random () * 2 is obviously coming out is [0 ~ 2) between the decimal, he passed with 0 or the way, the fractional part is removed, cool! the principle of this approach is that using
JavaScript to do bitwise operations (bitwise operation) will first change the operand through an unsigned right shift to a 32-bit integer , while with 0 the bitwise OR obviously does not alter the value of the integer, So it's possible to convert decimals into integers and get rid of fractional parts. So we should be able to guess (true | 0) will get 1, "123" | | will get 123. Similarly, the same goal can be achieved by the & 4294967295 approach. In fact, there are several simple ways to get rid of fractional parts to convert decimals into integers, listed below The second kind: Two-time inversion, the same is the use of bit operation conversion principle.
var integer = ~~decimal; 4 = ~~4.123
The third type: mathematical functions that take integers up and down, Math.ceil and Math.floor
var integer = decimal >= 0? Math.floor (decimal): Math.ceil (decimal);
Of course there are more complicated ways, but after the Robert Koritnik test, or with 0 or the way faster, it is recommended that you use:)Attach test Connection http://jsperf.com/truncating-decimals However, I would like to remind you that the first and second ways are required for the scope of the operand (because it is converted to a 32-bit integer), so if the value itself exceeds the range represented by the 32-bit integer, the error will result if the information is lost. Like 2147483648 | The result of 0 is-2147483648. The result of ~~4294967296 is 0. A 32-bit signed integer maximum is 2147483647, so this method requires the integer portion of the decimal to be between 2147483648 and 2147483647.
JavaScript decimal converts to integers