Sunday, November 30, 2008

Rounding numbers

Previous posts touched on the subject of formatting numbers; either as formatting currency or separating with commas and two decimal places. Another question that's frequently asked is how to round to different numbers of decimal places?

The standard answer is to use powers of 10 as per the following examples. To round to two decimal places use:
roundedNumber =  Math.round(yourNumber * 100)/100;

For three decimal places, use:
roundedNumber =  Math.round(yourNumber * 1000)/1000;

However, an easier way is to create a quick function to perform the work for you:

function roundDecimal(num:Number, places:Number):Number {
// defaults to two decimal places
if (places == null) {
places = 2;
power = Math.pow(10, places);
return Math.round(num * power) / power;

Use it as follows:

trace(roundDecimal(3.14159265358979, 5)); // Outputs 3.14159
trace(roundDecimal(3.14159265358979, 3)); // Outputs 3.142

No comments: