## Round-off numbers in Javascript

·   ·  ☕ 1 min read

How do you round-off a number in Javascript?

The simple way -

 1 2 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

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

Use ceil.

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

Use trunc.

 1 2 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.

 1 2 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 -

 1 2 3 4 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.

 1 2 3 4 5 console.log(~3.14); // -4 console.log(~-4); // 3 // or simply.. console.log(~~3.14); // 3
Stay in touch!
Share on

WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things