Wednesday, May 16, 2012

Custom Currency Format using as3

Here I'm going to share about Currency Formatter class in Action Script 3.
Using this, we may change currency format in flex. By default, This class return an string "-$100", for the Input "-100". But, while we undoing this, we only get "100"(It excludes negative sign which before Currency Symbol, whatever it may be) . This is because, Currency formatter doest mind any symbol before currency symbol. Even though, we using "useNegativeSign" property as true.

In default, the class first assign sign,then symbol, then number.In base class, i.e, in CurrencyFormatter.as class is as follows:

if (alignSymbol == "left")
{
      if (isNegative)
{
                var nSign:String = numStr.charAt(0);

                var baseVal:String = numStr.substr(1, numStr.length - 1);
                numStr =   nSign + currencySymbol +  baseVal;       
            }
else
{
                numStr = ncurrencySymbol + numStr;
            }
        }
}



Remedy is, we have to create Custom class for CurrencyFormatter. We have to override a format() function.

We just change that format to our needs, like first symbol and followed by sign, then numbers.

if (super.alignSymbol == "left")
{
        if (isNegative)
{
                var nSign:String = numStr.charAt(0);

                var baseVal:String = numStr.substr(1, numStr.length - 1);
                numStr =  super.currencySymbol + nSign +  baseVal;      
            }
else
{
                numStr = super.currencySymbol + numStr;
            }
        }
}

After this, we may create an instance for our custom Currency class in usual way. And assign properties whatever we need. Say an example, I'm creating custom class instance for my CustomCurrency Format class.

             var m:MyCurrencyFormat = new MyCurrencyFormat();
            m.precision = 2;
            m.useThousandsSeparator = true;
            m.currencySymbol = "£";
             result.text = m.format(txtInput.text);




Hope, May this post help somebody!!!