How do you round-off a number in Javascript?
The simple way -
|
|
Then, there are other interesting ways..
Round off to the nearest lower whole number
Use Math.floor
instead of round
.
|
|
Round off to the nearest higher whole number
Use ceil
.
|
|
Just truncate the fraction
Use trunc
.
|
|
Use a simple, fast way using ~~
The double tilde operator has an output like trunc
.
|
|
.. 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 -
|
|
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.
|
|