'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
?
Solution 1:[1]
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!
Solution 2:[2]
this is a good example i think
var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );
Solution 3:[3]
just do: ~~(x + 0.5)
Cheers, Z.
Solution 4:[4]
Arithmetic OR with zero does the trick.
> 12 === (0 | 12.245)
true
Solution 5:[5]
If you don't care about the rounding specifics, Math.trunc()
is easy, standard, and readable. I haven't tested performance, but it must be better than Math.round()
and parseInt()
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Firefog |
Solution 3 | zi88 |
Solution 4 | Ezward |
Solution 5 | Jacktose |