I couldnt believe the Math.round() function in AS3 is so crippled. All it returns is the nearest integer value and ofcourse there is no way you can specify what is the precision of rounding. To make it worse it always rounds 1.5 to 1. Hmmm..

But the solution to this problem is pretty simple. For example if u want a 2 decimal place rounding all we have to do is multply with 100,then round it and then divide it by 100. Confusing..well here is the code:

public static function roundDecimal(num:Number, precision:int):Number{

var decimal:Number = Math.pow(10, precision);

return Math.round(decimal* num) / decimal;

}

Well that was pretty simple right. Now go coding..all the best.

### Like this:

Like Loading...

*Related*

Heh, neat trick. You’d really think they’d have a more sophisticated rounding function, though.

yeah sure…just remember this code cant give u the trailing zeroes.ie, if u round

2.90003 to 3 decimals it will give only 2.9 and not 2.900..so if we need that for some displaying purposes, we have to add it manually..

I found that if you want to get specific with decimal the best way to do this is with the toFixed(length) function built into as3.

ex:

var myNum:int = new int(3.454954849584)

myNum.toFixed(3);

trace(myNum); // 3.454

Really takes the effort out.

You can also do precision based decimal rounding with the toPrecision, this will round the last decimal outside the length parameter.

myNum.toPrecision(3);

trace(myNum); // 3.455;

From: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Number.html

wow..thats something really cool..i wish i knew it while i was in need of it..

var roundedDecimal:Number = Number(myNum.toPrecision(6));

Communism is great!

LCD TVs are the mainstream stuff that you can buy today but their contrast ratio isn’t that great compard to CRT’s ..

Number not int

var myNum:Number = new Number(3.454954849584)

myNum.toFixed(3);

trace(myNum); // 3.454

and below 3.45 not 3.455

myNum.toPrecision(3);

trace(myNum); // 3.45;

trace(Math.round(1.5)); // 2 … no idea what you’re talking about.

try this out:

Math.round(getTimer()/1000*100)/100