I am making a function that receives a positive number and then rounds the number to the closest integer bellow it.
I have been usi
Actually, there is much more alternative ways to remove the decimals from a number. But it's a tradeoff of 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()
are conceptually very different from trunc()
.
You already know these. Always use them in a standard, non-critical code.
var v = 3.14;
[Math.trunc(v), Math.floor(v), Math.ceil(v), Math.round(v)]
// prints results
for different input values you get these results
t f c r
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 this is more fun :)
If you look at them in the code, it might not be apparent from the first glance what they do, so don't use them in normal code. Though in some cases, they might be useful. For example calculating coordinates in a <canvas/>
. They are much faster, but come with limitations.
ATTENTION:
Numbers with more than 32 bits get their most significant (leftmost) bits discarded and the leftmost bit becomes the new sign bit.[ 0b011100110111110100000000000000110000000000001, // 15872588537857 ~~0b011100110111110100000000000000110000000000001, // -1610588159 ~~0b10100000000000000110000000000001, // -1610588159 ]
value
to be shifted and a number
of bit positions to shift the value
by. However, when truncating, we always use a 0
, zero, a false
as a second operand, that doesn't do anything to the original value, except for converting to integer, in these cases:
~
NOT ~~v
|
OR v | 0
<<
Left shift v << 0
>>
Signed right shift v >> 0
>>>
Zero-fill right shift v >>> 0
var v = 3.78;
[ ~~v , v | 0 , v << 0 , v >> 0 , v >>> 0 ]
// prints these results
3.78 : [ 3, 3, 3, 3, 3]
3.14 : [ 3, 3, 3, 3, 3]
-3.74 : [-3, -3, -3, -3, 4294967293]
-3.14 : [-3, -3, -3, -3, 4294967293]
https://jsperf.com/number-truncating-methods/1
if the argument is a positive number, Math.trunc() is equivalent to Math.floor(), otherwise Math.trunc() is equivalent to Math.ceil().
for the performance check this one and the fastest one is Math.trunc
var t0 = performance.now();
var result = Math.floor(3.5);
var t1 = performance.now();
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:', result);
var t0 = performance.now();
var result = Math.trunc(3.5);
var t1 = performance.now();
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:', result);
the result is Took 0.0300 milliseconds to generate: 3 Took 0.0200 milliseconds to generate: 3
so if the arguments are only positive numbers you can use the fastest one.