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.




[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;
}
]]>





It looks like this:

Leave a Reply