Last Updated: February 25, 2016
·
722
· 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