Bytes won’t bite …

Networks | OS | Games | Fun | 11111000011

Decimal rounding in Actionscript 3

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.

July 10, 2009 - Posted by swordfish1987 | Actionscript | , , , , , | 4 Comments

4 Comments »

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

    Comment by probabilityzero | July 10, 2009 | Reply

    • 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..

      Comment by swordfish1987 | July 10, 2009 | Reply

  2. 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

    Comment by Scott Haines | July 28, 2009 | Reply

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

      Comment by swordfish1987 | July 28, 2009 | Reply


Leave a comment