Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to cast a float to an int in javascript?

Let's say I have x = 12.345. In javascript, what function floatToInt(x) has the fastest running time such that floatToInt(12.345) returns 12?

like image 694
ambient Avatar asked Dec 03 '15 22:12

ambient


1 Answers

Great Question! I actually had to deal with this the other day! It may seem like a goto to just write parseInt but wait! we can be fancier.

So we can use bit operators for quite a few things and this seems like a great situation! Let's say I have the number from your question, 12.345, I can use the bit operator '~' which inverts all the bits in your number and in the process converts the number to an int! Gotta love JS.

So now we have the inverted bit representation of our number then if we '~' it again we get ........drum roll......... our number without the decimals! Unfortunately, it doesn't do rounding.

var a = 12.345;
var b = ~~a; //boom!

We can use Math.round() for that. But there you go! You can try it on JSperf to see the slight speed up you get! Hope that helps!

like image 116
Hunterrex Avatar answered Sep 19 '22 16:09

Hunterrex