'Math.floor VS Math.trunc JavaScript

Background

I am making a function that receives a positive number and then rounds the number to the closest integer bellow it.

I have been using Math.floor, but recently I discovered Math.trunc.

I am aware that both will return the same value, given a positive number, and that they work in completely different ways. I am interested in exploring this behavior.

Questions

  1. Which one is faster ?
  2. Which one should I use?


Solution 1:[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.

Solution 2:[2]

The existing answers have explained well about the performance. However, I could not understand the functional difference between Math.trunc and Math.floor from either the question or the answers and hence I have put my finding in this answer.

Math.trunc rounds down a number to an integer towards 0 while Math.floor rounds down a number to an integer towards -Infinity. As illustrated with the following number line, the direction will be the same for a positive number while for a negative number, the directions will be the opposite.

trunc: towards 0    
floor: towards -Infinity


                   -3      -2     -1      0      1      2      3
-Infinity ... ------+----|--+------+------+------+------+--|----+------ .... Infinity
                         b                                 a    

Demo:

var a = 2.3, b = -2.3;
console.log("\t\t\t" + a + "\t\t" + b + "\r\n" + "Math.trunc: " + Math.trunc(a) + "\t\t" + Math.trunc(b) + "\r\n" + "Math.floor: " + Math.floor(a) + "\t\t" + Math.floor(b));

Output:

            2.3     -2.3
Math.trunc: 2       -2
Math.floor: 2       -3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kaleab
Solution 2 Eric Goerens