views:

6897

answers:

4

I have an xml file providing data for a datagrid in Flex 2 that includes an unformatted Price field (ie: it is just a number). Can anyone tell me how I take that datafield and format it - add a currency symbol, put in thousand separators etc. Thanks. S.

A: 

How about the CurrencyFormatter class

See here for docs from Flex 2. It's pretty easy to use.

You can use one of these in a labelFunction on a DataGrid Column to format your numbers.

Simon
+2  A: 

As stated above an easy way to do this would be to add a labelFunction to the specified column and format the data within there.

Frequently I find that its much easier to work with objects then straight XML so normally if I am receiving XML from a function I would create an object and parser for that XML and you can format the data inside the parser also if you like.

Another way to handle this would be inside an itemRenderer. Example:

<mx:DataGridColumn id="dgc" headerText="Money" editable="false">
    <mx:itemRenderer>
      <mx:Component>
         <mx:HBox horizontalAlign="right">
     <mx:CurrencyFormatter id="cFormat" precision="2" currencySymbol="$" useThousandsSeparator="true"/>
            <mx:Label id="lbl" text="{cFormat.format(data)}" />
         </mx:HBox>
      </mx:Component>
    </mx:itemRenderer>
</mx:DataGridColumn>
JustFoo
This is unnecessarily complex. The point of the labelFunction is to avoid the overhead of an itemRenderer per cell in the column. In the example above you also have a CurrencyFormatter per cell. The questioners solution below is a better alternative.
Simon
Yes I understand that I was just giving an alternative, hence why the first line I stated to use the label function.
JustFoo
+3  A: 

Thanks alot for your answers...they helped a great deal.

In the end I went for a solution that involved the following three elements:

<mx:DataGridColumn headerText="Price" textAlign="right"  labelFunction="formatCcy" width="60"/>

public function formatCcy(item:Object, column:DataGridColumn):String
    {
   return euroPrice.format(item.price);
    }

<mx:CurrencyFormatter id="euroPrice" precision="0" 
    rounding="none"
    decimalSeparatorTo="."
    thousandsSeparatorTo=","
    useThousandsSeparator="true"
    useNegativeSign="true"
    currencySymbol="€"
    alignSymbol="left"/>

I dont know whether this is the correct solution, but it seems to work (at the moment), Thanks again, S...

This is exactly the right solution, there's no need for an itemRenderer if all you are doing is formatting the contents of cells.
Simon
yes Simon . This is the right solution . i fully agree with you
R.Vijayakumar
A: 

Cheers Guys

Worked a treat for me