Custom Number Formatting in Flex.

A quick intro before I start. I’m Rudy and I’m a new contributor here.

Lately I’m doing a lot of flex programming and although Adobe Flex is quite mature (It has reached version 4.5 this year), I feel that the language is still lack of support to business. One of the missing feature is Number/Currency Formatting that accepts pattern as a template format.

In Flex, we have <mx:CurrencyFormatter>[link]. However it does not accept Pattern. In addition, it’s implemented as a tag which does not allow to be invoked in ActionScript. However, in Java this capability is being implemented nicely using DecimalFormat [link].

Based on the reasons above I decided to create my own formatter that can be called from both ActionScript and mxml. Note that since this is just a quick hack, the code maybe a little bit messy.

Currently it able to cater currency symbol, percentage, # and 0. For example :

  • 1234.56 with pattern #,###.## has output 1,234.56
  • 1234.56 with pattern USD#,###.## has output USD 1,234.56
  • 1234.56 with pattern $#,###.## has output $ 1,234.56
  • 1.23 with pattern 000.000 has output 001,230
  • -12.34 with pattern USD0##.## has output -USD 012.34
  • 123.45 with pattern ###.##% has output 123.45%

Usage :

var nf:NumberFormatter = new NumberFormatter();
var number:Number = 1234.56;
nf.formatString = "#,###.##";
var resultFormatted:String = nf.format(number);

You can download the full code in http://goo.gl/xhBtM