7

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?

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201
  • possible duplicate of [What is the "double tilde" (~~) operator in JavaScript?](http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript) – Tomasz Nurkiewicz Dec 12 '12 at 19:25

2 Answers2

15

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
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • You could also do `~~n - (n < 0)`, but that's just cruel. – Blender Dec 12 '12 at 19:27
  • It **is** playing well with negative numbers if you want to round toward zero, instead of round toward minimum, something I run into often for whatever reason... – Myndex Oct 28 '20 at 21:35
8

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
a--m
  • 4,716
  • 1
  • 39
  • 59