EN
JavaScript - number truncation (getting total part)
10
points
In this short article, we would like to show how to truncate numbers in JavaScript.
As truncation, we understand the total part of number extracting, keeping number sign.
Quick solution:
// ONLINE-RUNNER:browser;
// ES5 and older
var number = 3.14;
console.log(number < 0 ? Math.ceil(number) : Math.floor(number)); // 3
// ES6+
console.log(Math.trunc(3.14)); // 3
Alternative approaches
It is possible to get the same effect with bit operators (Bitwise Shift, Bitwise OR, and Bitwise NOT).
Warning: the solution converts numbers to 32 bits.
// ONLINE-RUNNER:browser;
console.log(3.14 << 0); // 3
console.log(3.14 >> 0); // 3
console.log(3.14 | 0); // 3
console.log(~~3.14); // 3