Last Updated: February 25, 2016
·
962
· bahlor

Quick float to integer (good canvas rendering method)

A really quick way converting floats to integers is by using the double not bitwise operator (~~) In game development its really a slowdown if you have to calculate many many items on the screen and want to render them, some still render floating coordinates which an absolute no go. There is nothing like 4.12 px. However there is a really quick way of just stripping off the decimals.

var base = ~~(4.12);  // this will output 4

Only one thing should be mentioned. Its actually just cutting off the decimals, so be sure to use this only where it doesn't matter. for example directly before rendering.

jsFiddle Demo

jsPerf Comparison of round,tofixed and bitwise

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside