Round-off numbers in Javascript

How do you round-off a number in Javascript?

The simple way -

console.log(Math.round("3.14")); // 3
console.log(Math.round("3.72")); // 4

Then, there are other interesting ways..

Round off to the nearest lower whole number

Use Math.floor instead of round.

console.log(Math.floor("3.14")); // 3
console.log(Math.floor("3.72")); // 3
Round off to the nearest higher whole number

Use ceil.

console.log(Math.ceil("3.14")); // 4
console.log(Math.ceil("3.72")); // 4
Just truncate the fraction

Use trunc.

console.log(Math.trunc("3.14")); // 3
console.log(Math.trunc("3.72")); // 3
Use a simple, fast way using ~~

The double tilde operator has an output like trunc.

console.log(~~3.14); // 3
console.log(~~3.72); // 3

.. but, it goes about doing the truncation in an altogether different way.

As you would know already, ~ is a bitwise NOT operator. It functions in a fairly simplistic way -

console.log(~3.14); // -4
console.log(~"a"); // -1
console.log(~0); // -1
console.log(~null); // -1

For a fraction, ~ converts the number into a 32-bit integer and shifts/negates it. Doing a ~ again on the bitwise-shifted number will bring it back to the positive side with the whole number intact, and again shifts a bit.

Ergo, truncation.

console.log(~3.14); // -4
console.log(~-4); // 3

// or simply..
console.log(~~3.14); // 3
comments powered by Disqus