Fastest way to cast a float to an int in javascript?
Solution 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
this is a good example i think
var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );
Solution 3
just do: ~~(x + 0.5)
Cheers, Z.
Solution 4
Arithmetic OR with zero does the trick.
> 12 === (0 | 12.245)
true
Comments
-
ambient almost 2 years
Let's say I have
x = 12.345
. In javascript, what functionfloatToInt(x)
has the fastest running time such thatfloatToInt(12.345)
returns12
?-
Bergi over 8 yearsAre there multiple functions that do your job?
-
Bergi over 8 yearsJust use
Math.round
(orMath.floor
, depending what you need). -
jfriend00 over 8 yearsIs the speed of your conversion really worth making less readable code?
-
ambient over 8 years@Bergi - is that the fastest way? Consider Hunterrex's insight below. How does the bitwise operator compare to Math.round or Math.floor?
-
jfriend00 over 8 yearsAnd, you've done performance testing on your code and found that an integer conversion is the main bottleneck? I ask this because most of the time people spend time "speeding things" up, they are actually working on the wrong part of the problem and thus wasting their time and oftentimes complicating their code without much or any improvement.
-
Bergi over 8 years@cody: You were asking for a function, not an operation, and I'm not aware of anything else. Also, speed does not matter.
-
Bergi over 8 years
-
Bergi over 8 years
-
ambient over 8 years@Bergi - you're in the forest and can't see the trees. I asked a simple question and was just looking for a simple answer, it is no more complicated than that. Thanks for the contribution, though!
-
Henke almost 3 yearsDoes this answer your question? How can I round down a number in Javascript?
-
-
Hunterrex over 8 yearsFor example: `var a = 12.345'
-
ambient over 8 yearsThis is a great suggestion! Can you provide an example please?
-
jfriend00 over 8 yearsAn answer to a "fastest" question with NO documentation or supporting evidence showing your method is faster in multiple browsers is missing a lot. It may be faster, but you should show some evidence that it actually is faster in multiple browsers.
-
jfriend00 over 8 yearsThat's not a very well designed performance test. It assumes that
Math.random()
always takes the exact same amount of time and that converting any possible result to an integer is always a constant time too. You should not haveMath.random()
in your test at all and you should be comparing a conversion of the same number for each method. Your method probably is faster, but this is a poorly designed test. When I run your test in Chrome, I see no meaingful difference between the first three methods. -
ambient over 8 years@Hunterrex that is some compelling evidence.
-
jfriend00 over 8 years@cody - How is that compelling? The first three methods show basically the exact same performance.
-
Hunterrex over 8 years@jfriend00 I did not write these tests, but I agree. I would write better tests, but a little strained for time.
-
Bergi over 8 years@jfriend00: Agreed on "no meanigful difference", but
Math.random
is pretty much necessary for these kind of tests. It ensures that the operation is not constant-folded by an optimising compiler. Oh, microbenchmarks are hard… -
jfriend00 over 8 yearsSo, you write an answer to a question asking for the "fastest" method that shows no meaningful difference when using someone else's test and you have no time to make a test of your own? You haven't shown your answer is anything other than a "different" method of converting to an int. And, I'm even more surprised that the OP took the bait and seems to think this is a good way to code.
-
jfriend00 over 8 years@Bergi -
Math.random()
has to be outside the timed region so you can time only the operation that actually matters. -
Bergi over 8 years@jfriend00: I don't think you can time a single
Math.round
call or~~
operation with the tools that JS gives you. And if you're timing a loop (like jsperf does),Math.random()
has to go in the body. But we can reasonably assume that everyMath.random()
call takes the same time (on average, at least), so that we can still compare the differences of the other operations. -
jfriend00 over 8 years@Bergi - Why can't you do this: jsperf.com/float-to-int-conversion-comparison/27. This times 1000 calls of an array of random numbers where the array is pre-built outside the timed loop and the same randoms are used for each test case.
-
Bergi over 8 years@jfriend00: Notice that the test code runs multiple times (in a loop with dynamic length) after each initialisation ("setup code"), so you should not mutate
testNumbers
, it would only consist of integers after the first run. You'd need to move theslice
inside the timed region. But the idea is good, if you don't trustMath.random
, you should be able to do something like that -
jfriend00 over 8 years@Bergi - I see your point about the setup code. I changed it to just assign to a
resultArray
so thetestNumbers
array is never disturbed so no.slice()
is needed and it always runs on the random numbers: jsperf.com/float-to-int-conversion-comparison/30. -
Toxiro about 4 yearsBe careful! With
x = 10000000000
:Math.floor(x) === x
, but~~x === 1410065408
.Math.floor(-0.5) === -1
, but~~(-0.5) === 0
-
Chiu almost 4 yearsuse
b = ~~(a + 0.5)
for rounding