Fastest way to cast a float to an int in javascript?
Asked Answered
P

7

23

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?

Prater answered 3/12, 2015 at 22:28 Comment(10)
Are there multiple functions that do your job?Jessie
Just use Math.round (or Math.floor, depending what you need).Jessie
Is the speed of your conversion really worth making less readable code?Tortuous
@Jessie - is that the fastest way? Consider Hunterrex's insight below. How does the bitwise operator compare to Math.round or Math.floor?Prater
And, 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.Tortuous
@cody: You were asking for a function, not an operation, and I'm not aware of anything else. Also, speed does not matter.Jessie
also duplicate of What is the best method to convert floating point to an integer in JavaScript?Jessie
@cody: ~~ has important edge cases you would need to consider. And it might not be faster at all.Jessie
@Jessie - 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!Prater
Does this answer your question? How can I round down a number in Javascript?Onshore
B
47

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!

Bossism answered 3/12, 2015 at 22:29 Comment(18)
For example: `var a = 12.345'Bossism
This is a great suggestion! Can you provide an example please?Prater
An 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.Tortuous
That'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 have Math.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.Tortuous
@Bossism that is some compelling evidence.Prater
@cody - How is that compelling? The first three methods show basically the exact same performance.Tortuous
@Tortuous I did not write these tests, but I agree. I would write better tests, but a little strained for time.Bossism
@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…Jessie
So, 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.Tortuous
@Jessie - Math.random() has to be outside the timed region so you can time only the operation that actually matters.Tortuous
@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 every Math.random() call takes the same time (on average, at least), so that we can still compare the differences of the other operations.Jessie
@Jessie - 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.Tortuous
@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 the slice inside the timed region. But the idea is good, if you don't trust Math.random, you should be able to do something like thatJessie
@Jessie - I see your point about the setup code. I changed it to just assign to a resultArray so the testNumbers 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.Tortuous
Be careful! With x = 10000000000: Math.floor(x) === x, but ~~x === 1410065408 . Math.floor(-0.5) === -1, but ~~(-0.5) === 0Pancreas
use b = ~~(a + 0.5) for roundingIndicate
@Bossism Could you add a warning for cases like x = 10000000000?Polis
Boom indeed! I'm not JS dev, but looks like if the number is bigger than int32 then you have a problem of negative result: ~~2147483648.88 gives -2147483648.Trilateration
O
14

this is a good example i think

var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue ); 
var intvalue = Math.round( floatvalue );
Orion answered 3/12, 2015 at 22:32 Comment(0)
A
8

just do: ~~(x + 0.5)

Cheers, Z.

Arturo answered 19/5, 2018 at 8:27 Comment(0)
M
6

Arithmetic OR with zero does the trick.

> 12 === (0 | 12.245)
true
Mcallister answered 5/7, 2020 at 21:38 Comment(0)
T
2

parseInt(x) does the work.
If you were running checks to see if the returned value is actually an int without the knowledge of what is the input.

x = 12.245; // Issa number
x = 'School'; // Not a number
y = parseInt(x)
if isNaN(y)
    console.log('Not a number');
else
    console.log('Issa number');
// Issa number

while using y = ~~x is a totally different case

x = 12.245; // Issa number
x = 'School'; // Issa number
y = ~~x;
if isNaN(y)
    console.log('Not a number');
else
    console.log('Issa number');

Technicality answered 5/10, 2022 at 20:22 Comment(0)
C
2

In my own testing, I've found that the rule of thumb for performance is:

  1. Bitwise operations (~~num, num|0, num^0, num&0xFFFFFFFF)
  2. Math methods
  3. num - (num % 1)
  4. parseInt

The issue with bitwise operators is that the numbers will be cast to 32bit integers in the process, if that is fine for your use-case then go ahead. See MDN docs on bitwise OR, bitwise NOT, bitwise AND and bitwise XOR or their respective ECMAScript documentation.

The parseInt function is usually way slower than the alternatives, most likely because it expects a string as parameter.

The solution with the modulo operator should be used with caution as it may bite you in the ass sometime due to floating point issues but is almost as fast as the Math methods.

Clemenceau answered 1/12, 2022 at 16:18 Comment(0)
F
0

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().

Fireresistant answered 15/4, 2022 at 5:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.