Languages
[Edit]
EN

JavaScript - number truncation (getting total part)

10 points
Created by:
Cassia
1145

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

 

See also

  1. JavaScript - how to get decimal part of float number?

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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