Archive

Posts Tagged ‘Math.ceil’

JavaScript Float to Int

April 17, 2011 Leave a comment

In JavaScript how can you convert a float like 3.3333 to just 3. Well there are many ways like Math.floor, Math.ceil, Math.round, parseInt, and toFixed(0). One problem which is fastest and what are the results of the new number? I made a test page that finds this out by looping 10000000 times converting the number 5.97655676758 into a integer and outputting the new number and time it took to compute.

  var j = 5.97655676758;
  //Math.floor  
  start = new Date();
  for (var i = 0; i <10000000; i++) {
    var k = Math.floor(j);
  }
  document.getElementById('results').innerHTML = "Floor: " + (new Date() -start) + " Result: " + k + "<br/>";
  //Math.ceil
  start = new Date();
  for (var i = 0; i <10000000; i++) {
    var k = Math.ceil(j);
  }
  document.getElementById('results').innerHTML += "Ceil: " + (new Date() -start) + " Result: " + k + "<br/>";
  //Math.round
  start = new Date();
  for (var i = 0; i <10000000; i++) {
    var k = Math.round(j);
  }
  document.getElementById('results').innerHTML += "Round: " + (new Date() -start) + " Result: " + k + "<br/>";
  //parseInt
  start = new Date();
  for (var i = 0; i <10000000; i++) {
    var k = parseInt(j);
  }
  document.getElementById('results').innerHTML += "parseInt: " + (new Date() -start) + " Result: " + k + "<br/>";
  //toFixed
  start = new Date();
  for (var i = 0; i <10000000; i++) {
    var k = j.toFixed(0);
  }
  document.getElementById('results').innerHTML += "toFixed: " + (new Date() -start) + " Result: " + k + "<br/>";

The results were:
Mac OS X 10.6.7 Safari
Floor: 294 Result: 5
Ceil: 316 Result: 6
Round: 337 Result: 6
parseInt: 868 Result: 5
toFixed: 4025 Result: 6
Mac OS X 10.6.7 FF4
Floor: 151 Result: 5
Ceil: 164 Result: 6
Round: 173 Result: 6
parseInt: 122 Result: 5
toFixed: 1721 Result: 6

From these results we can see that for speed Math.floor is the best being the fastest in Safari and second fastest in FF4. While for both speed and accuracy Math.round is king.