Original url at https://siderite.dev/blog/getting-integer-part-from-number-in-javascript
Just a thing I learned today: using the bitwise not operator (~) on a number in Javascript ignores its fractional part (it converts it to integer first), therefore using it twice gives you the integer part of original number. Thanks to fetishlace for clarifications.
Notes:
- this is equivalent to (int)number in languages that support the int type
- this is equivalent to Math.trunc for numbers in the integer range
- this is equivalent to Math.floor only for positive numbers in the integer range
Examples:
~~1.3 = 1
~~-6.5432 = -6
~~(2 ** 32 + 0.5) = 0
~~10000000000 = 1410065408
Top comments (3)
It works as a Math.trunc(), but be careful if u need to use it with a big numbers since for example
~~(2 ** 30 + 0.123) // 1073741824
~~(2 ** 31 + 0.303) //-2147483648
~~(2 ** 32 + 0.5) // 0
Thanks! To my shame I've never actually used either Math.trunc or ** in Javascript :D Live and learn. I'll update the post.
Various people prefer various tools, it is not the shame i guess :-)
** is newer and handy, way better 2**16 than write Math.pow(2,16)
And I would rather use Math.trunc() than Number.parseInt() - which is in play here too. In fact parseInt(inputValue, 10) with explicit radix argument is the right way to go according to Airbnb standards.
That double bit flip ~~ looks nice and short, and it could run faster than others - that is why it has it's place - but some people are really confused seeing it + this is not a bottleneck normally anyway + it "breaks" sooner than those alternatives for higher numbers...
Anyway I am seeing all of these in other people's code.