Code & Craft
Posted on
Code

An simple alternative to parseInt in javascript

Author

Am I the last person in the world to discover this?

One way to round off numbers in Javascript is to use the parseInt method. Like so.

var someRandomNumber = 123.1872;
var roundedOff = parseInt(someRandomNumber);

Remember though that parseInt does not actually round, it truncates the decimal portions of the number.

But that's not the point. I don't know how good parseInt is performance wise, but an easier way to round off (or truncate the decimal parts) numbers in Javascript is to right-shift a number by 0. Like so.

var someRandomNumber = 123.1872;
var roundedOff = someRandomNumber >> 0;

Both these examples yield 123 as the result.

So I did some performance tests to see which one performed better. Each method was run a 1,000, 10,000 and 100,000 times and the time was noted. The tests themselves were carried out 20 times.

I did not see a great deal of difference when the tests were ran a 1,000 times. Each method ran for more or less a millisecond, however I have to say that over 20 times, the right-shift edged out.

There was still no big difference when the tests were ran 10,000 times. Still, right-shift edged out.

The big difference was when it was run 100,000 times. The right-shifting outperforms parseInt as a method to round off (or truncate) number.

Here's the result of 20 runs. Each run was 100,000 conversions.

# ParseInt Right-Shift
1 9 5
2 4 1
3 5 1
4 3 1
5 2 1
6 3 1
7 3 1
8 3 0
9 4 1
10 3 0
11 3 1
12 3 1
13 3 1
14 3 0
15 3 1
16 3 1
17 3 1
18 3 1
19 3 0
20 3 1
Average 3.45 1

Here's the code if you want to do this yourself.

var testing = "ParseInt - Right-Shift\n";
for(j=0; j<20; j++)
{
  var startTime = new Date().getTime();
  for(i=0; i<100000; i++)
  {
    var myVar = Math.random() * 1970;
    var roundOff = parseInt(myVar);
  }
  var endTime = new Date().getTime();
  var timeTaken = endTime - startTime;
  testing += timeTaken + " - ";

  startTime = new Date().getTime();
  for(i=0; i<100000; i++)
  {
    var myVar = Math.random() * 1970;
    var roundOff = myVar >> 0;
  }
  endTime = new Date().getTime();
  timeTaken = endTime - startTime;
  testing += timeTaken + "\n";
}
alert(testing);