CMXtraneous

Right on the edge of useful

How to Round to the Nearest Ten, Tenth, Hundred, Hundredth, Etc.

Posted Friday, April 06, 2007 12:19:48 PM by David Stiller

David Stiller

I was helping a friend the other day with a rounding issue.  He needed to round numbers not to the nearest integer, but to the nearest hundred.  So 52.3 would round to 100.  86 would round to 100 as well.  13 would round to 0 and 101.287 would round to 100.  You get the idea.  The Math.round() method doesn’t take any parameters except the to-be-rounded value itself, so how could this be accomplished?  The answer couldn’t be simpler.

An answer, short and sweet

Basic arithmetic does it.  Let’s say the original number is 52.3.  To round to the nearest hundred, follow these steps:

  • Divide by 100
  • Round
  • Multiply by 100
var num:Number = 52.3;
num /= 100;
num = Math.round(num);
num *= 100;
trace(num);

How it works

The above ActionScript could have been written out a bit longer …
num = num / 100;

… but the division assignment (/=) operator reduces the required typing.  They amount to the same thing (and the same goes for the multiplication assignement (*=), as well as addition and subtraction assignment operators (+= and -=).

The division/multiplication steps move the decimal place where it needs to go.  The rounding functions as it always does.

Variation

If you need to round to the nearest hundredth — 189.5287 becomes 189.53 — just reverse the division and multiplication steps:

var num:Number = 52.3;
num *= 100;
num = Math.round(num);
num /= 100;
trace(num);

Category tags: Flash