Decimal rounding in Actionscript 3

Posted: July 10, 2009 in Actionscript
Tags: , , , , ,

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.

  1. 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, if u round
      2.90003 to 3 decimals it will give only 2.9 and not if we need that for some displaying purposes, we have to add it manually..

  2. Scott Haines says:

    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.


    var myNum:int = new int(3.454954849584)
    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.

    trace(myNum); // 3.455;


  3. leef says:

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

  4. Communist says:

    Communism is great!

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

  6. blez says:

    Number not int

    var myNum:Number = new Number(3.454954849584)
    trace(myNum); // 3.454

    and below 3.45 not 3.455

    trace(myNum); // 3.45;

  7. Josh says:

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

  8. Mark says:

    try this out:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s