Languages
[Edit]
EN

JavaScript - number truncation (getting total part)

10 points
Created by:
Cassia-Mendoza
415

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):

// 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

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join