In fact, there are many more alternative ways to remove decimal numbers from a number. But this is a compromise between readability and speed.
Choosing the right one depends on what you need. If you just need to remove decimals , always use trunc() or bitwise operators.
floor() , ceil() and round() conceptually very different from trunc() .
Math library
You already know that. Always use them in standard non-critical code.
var v = 3.14; [Math.trunc(v), Math.floor(v), Math.ceil(v), Math.round(v)]
for different input values you get these results
tfcr 3.87 : [ 3, 3, 4, 4] 3.14 : [ 3, 3, 4, 3] -3.14 : [-3, -4, -3, -3] -3.87 : [-3, -4, -3, -4]
But it's more fun :)
If you look at them in code, at first glance it may not be clear what they are doing, so do not use them in regular code. Although in some cases they may be useful. For example, calculating coordinates in <canvas/> . They are much faster, but come with limitations.
Conceptually, they work like this:
- The operands are converted to signed 32-bit integers and thus lose all decimal fractions. (Numbers containing more than 32 bits receive their most significant (leftmost) bits , discarded - usually a signed bit.)
[ ~~0b011100110111110100000000000000110000000000001, // -1610588159 - before ~~0b10100000000000000110000000000001, // -1610588159 - after ]
Bitwise logical operators
- Each bit in the first operand is associated with a corresponding bit in the second operand. (First bit to first bit, second bit to second bit, etc.)
- An operator is applied to each pair of bits, and the result is created bitwise.
Bitwise shift operations
- These operators accept
value for offset and number bit positions for offset value by.
truncation
However, when truncating, we always use 0 , zero, and false as the second operand, which does nothing with the original value, except for conversion to an integer, in the following cases:
~ NOT ~~v
| OR v | 0 v | 0
<< Left shift v << 0
>> Signed right v >> 0
>>> Shift to the right with zero filling v >>> 0
var v = 3.78; [ ~~v , v | 0 , v << 0 , v >> 0 , v >>> 0 ]
Performance
https://jsperf.com/number-truncating-methods/1
