Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ~~ and Math.floor()

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?

like image 560
Afshin Mehrabani Avatar asked Dec 12 '12 19:12

Afshin Mehrabani


1 Answers

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
like image 78
David Hellsing Avatar answered Sep 21 '22 23:09

David Hellsing