|
Flex Currency Formatter Example |
Whilst developing a new Flex shopping cart I came across an issue in dealing with the formatting of currencies for the payment system. The previous version of the shopping cart had preformatted values stored in the actual database, so I was simply displaying them in the Flex front end.
In this version there is the specific requirement that it is able to handle a multi currency configuration. So I thought I'd dig out the documentation on the Flex currency Formatter.
Firstly create a CurrencyFormatter object, and specify the currency symbol, and any other formatting parameters that you require.
Next create a NumberValidator, as this will validate our entered value as a numeric value, we don't need to try and re-format alpha numeric values.
Then create a form to run the test validation against. I often find it easier to build a test mechanism at the same time. Below is a simple submission form, in the form we just enter the value, click the Button, which fires the Format() function.
2<!-- Simple example to demonstrate the CurrencyFormatter. -->
3<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
4
5 <mx:CurrencyFormatter id="ukFormatter" precision="2"
6 currencySymbol="�" decimalSeparatorFrom="."
7 decimalSeparatorTo="." useNegativeSign="true"
8 useThousandsSeparator="true" alignSymbol="left"/>
9
10 <mx:NumberValidator id="numVal" source="{priceUK}" property="text"
11 allowNegative="true" domain="real"/>
12
13 <mx:Panel title="CurrencyFormatter Example" width="75%" height="75%"
14 paddingTop="10" paddingLeft="10" paddingRight="10" paddingBottom="10">
15
16 <mx:Form>
17 <mx:FormItem label="Enter U.K. dollar amount:">
18 <mx:TextInput id="priceUK" text="" width="50%"/>
19 </mx:FormItem>
20
21 <mx:FormItem label="Formatted amount: ">
22 <mx:TextInput id="formattedUKPrice" text="" width="50%" editable="false"/>
23 </mx:FormItem>
24
25 <mx:FormItem>
26 <mx:Button label="Validate and Format" click="Format();"/>
27 </mx:FormItem>
28 </mx:Form>
29
30 </mx:Panel>
31
32</mx:Application>
The Format() function checks that the value is numeric, and applies the CurrencyFormatter object to the value. Then we simply assign the newly formatted value back to our Text field in the form.
2 <![CDATA[
3
4 import mx.events.ValidationResultEvent;
5 private var vResult:ValidationResultEvent;
6
7 // Event handler to validate and format input.
8 private function Format():void {
9
10 vResult = numVal.validate();
11
12 if (vResult.type==ValidationResultEvent.VALID) {
13 var temp:Number=Number(priceUK.text);
14 formattedUKPrice.text= ukFormatter.format(temp);
15 }
16
17 else {
18 formattedUKPrice.text="";
19 }
20 }
21 ]]>
22 </mx:Script>