最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Difference between ~~ and Math.floor() - Stack Overflow

programmeradmin4浏览0评论

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/math-round-vs

So I want to know, is there any 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?

Share Improve this question asked Dec 12, 2012 at 19:22 Afshin MehrabaniAfshin Mehrabani 34.9k33 gold badges143 silver badges208 bronze badges 1
  • possible duplicate of What is the "double tilde" (~~) operator in JavaScript? – Tomasz Nurkiewicz Commented Dec 12, 2012 at 19:25
Add a comment  | 

2 Answers 2

Reset to default 16

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

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.

  • http://cwestblog.com/2011/07/27/limits-on-bitwise-operators-in-javascript/

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
发布评论

评论列表(0)

  1. 暂无评论