Math.floor VS Math.trunc JavaScript

前端 未结 2 525
刺人心
刺人心 2021-01-31 08:49

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 usi

2条回答
  •  渐次进展
    2021-01-31 09:10

    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.

提交回复
热议问题