Math.floor() and ~~

Published by on

Using the bitwise operators in JavaScript you can do all kinds of interesting things.

For example, it is possible to use the operator "bitwise negation" (the tilde ~) to round off numbers:

Using the bitwise operators in JavaScript you can do all kinds of interesting things.

For example, it is possible to use the operator "bitwise negation" (the tilde ~) to round off numbers:

It is helpful because rounding a number using the "bitwise negation" operator is much faster in many browsers than using Math.floor.

This feature is especially useful when rounding a number has to be repeated very often, such as when manipulating the pixel data of a <canvas> element where several thousand pixels have to be compared one by one.

Since I use exactly this use case in my projects (see for example glitch-canvas, I have used ~~ as a replacement for Math.floor() in general.

This was a mistake.

Because there are numbers for which the results of ~~ and Math.floor() not match:

It is helpful because rounding a number using the "bitwise negation" operator is much faster in many browsers than using Math.floor.

This feature is especially useful when rounding a number has to be repeated very often, such as when manipulating the pixel data of a <canvas> element where several thousand pixels have to be compared one by one.

Since I use exactly this use case in my projects (see for example glitch-canvas, I have used ~~ as a replacement for Math.floor() in general.

This was a mistake.

Because there are numbers for which the results of ~~ and Math.floor() not match:

Many shortcuts and hacks in code are helpful for special cases, but they should be used with caution and not generalized. That is why they are called shortcuts and hacks.

I learned something today, hope you did as well. Until next time!

Leave a comment

Available formatting commands

Use Markdown commands or their HTML equivalents to add simple formatting to your comment:

Text markup
*italic*, **bold**, ~~strikethrough~~, `code` and <mark>marked text</mark>.
Lists
- Unordered item 1
- Unordered list item 2
1. Ordered list item 1
2. Ordered list item 2
Quotations
> Quoted text
Code blocks
```
// A simple code block
```
```php
// Some PHP code
phpinfo();
```
Links
[Link text](https://example.com)
Full URLs are automatically converted into links.

Replied on your own website? Send a Webmention!