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:

Post a Comment