Question

As I see in examples, the functionality if ~~ and Math.floor is the same. Both of them round a number downward (Am I think correct?)

Also I should mention that according to this test ~~ is faster than Math.floor: jsperf.com/math-round-vs

So I want to know, is there any difference between ~~ and Math.floor?

Was it helpful?

Solution

Yes, bitwise operators generally don’t play well with negative numbers. f.ex:

~~-6.8 == -6 // doesn’t round down, simply removes the decimals

Math.floor(-6.8) == -7

And you also get 0 instead of NaN, f.ex:

~~'a' == 0

Math.floor('a') == NaN

OTHER TIPS

In addition to David answer:

One of the things that I have noticed about bitwise operations in JavaScript is that it can be convenient for smaller values, but doesn’t always work for larger values. The reason this is the case is that bitwise operators will only work fully for operands which can be fully expressed in a 32-bit signed format. In other words, using bitwise operations will only produce numbers that are in the range of -2147483648 (-231) to 2147483647 (231 – 1). In addition, if one of the operands used is outside of that range, the last 32 bits of the number will be used instead of the specified number.

This limitation can easily be found when working with Date, assume you are rounding a milliseconds value:

Math.floor(1559125440000.6) // 1559125440000
~~1559125440000.6           // 52311552
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top