How to format a number as money

Recently I was working on a project where I had to take a number that represented a monetary value and display it as money. For example say I had a numeric variable that contained the value of 10000 and I needed it to display like money with the commas and dollar sign like this $10,000. So in other words I needed the string representation. That is what this simple function that I am posting does. I have written it here in Flash ActionScript 3 as a static function of a class, but you could adapt it however you need to. Here is the code:

public class Formatter
{
    public static function formatMoney(val:int):String
    {
        var isNegative:Boolean = false;
        var moneyVal:String = val.toString();
        var len:uint;
        if(val < 0)
        {
             isNegative = true;
             moneyVal = moneyVal.replace(/-/, "");
        }
        len = moneyVal.length;
        for(var i:int=len; i>0; i-=3)
        {
            if(i == len)
            {
                continue;
            }
            var firstHalf:String = moneyVal.substring(0, i);
            var lastHalf:String = moneyVal.substring(i);
            moneyVal = firstHalf+","+lastHalf;
        }
        if(isNegative)
        {
            return"$-"+moneyVal;
        }
        return "$"+moneyVal;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *