How to implement Math.trunc() in JavaScript

1 Answer

0 votes
function trunc(n) {
    return Math.sign(n) * Math.floor(Math.abs(n));
}

console.log(trunc(2.1));
console.log(trunc(2.9));

console.log(trunc(-5.1));
console.log(trunc(-5.9));



/*
run:
 
2
2
-5
-5
    
*/

 



answered Mar 13, 2020 by avibootz
...