Using the Flex Datagrid’s “labelFunction”

Someone once asked me if they had a datagrid column that displayed millions, billions, and trillions of dollars, how could they render it in a non-numerical way so it would show as:

1,000,000 = 1 Million
1,000,000,000 = 1 Billion
1,000,000,000,000 = 1 Trillion

The other requirement is that it must still be in a numerical format to apply mathematical operations. Flex framework’s Datagrid component has a nice feature called “labelFunction” that lets you define your own custom label render so that you may apply your own rules. The following is one sample approach to the problem.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
  <mx:Script>
    <![CDATA[
      [Bindable]
      public var myDataProvider:Array = [  125000000.99,
                1700000000.01,
                984561321483.56,
                0.99,
                5.75,
                31400000000.01];
      
      public function myLabelFunction(item:Object, column:DataGridColumn):String
      {
        var amount:String = item.toString();
        var dollars:String = amount.split(".")[0];
        var dollarDigitCount:Number = dollars.toString().length;
        
        var value:String;
        
        if (dollarDigitCount >= 7 && dollarDigitCount <= 9)
        {
          value = dollars.slice(0, -6) + " Million";
        }
        else if (dollarDigitCount >= 10 && dollarDigitCount <= 12)
        {        
          value = dollars.slice(0, -9) + " Billion";
        }
        else if (dollarDigitCount >= 13)
        {
          value = dollars.slice(0, -12) + " Trillion";
        }
        else
        {
          value = item.toString();
        }
        
        return "$" + value;
      }
    ]]>
  </mx:Script>
 
  <mx:DataGrid id="dg" dataProvider="{myDataProvider}" >
    <mx:columns>
      <mx:DataGridColumn headerText="Click To Sort" labelFunction="myLabelFunction"/>
    </mx:columns>
  </mx:DataGrid>
  
  <mx:TextInput id="textInput" text="{dg.selectedItem}"/>
  
</mx:Application>

It looks like this:

Leave a Reply