I was looking at the NumberFormatter class this evening and made this little demo that shows the four different types of rounding (nearest, up, down, and none) in action.
The following example shows how you can use the static NumberFormatter class in conjuction with the NumberBaseRoundType constants to round and format numbers based on a certain criteria.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/12/13/rounding-numbers-in-flex-using-the-numberformatter-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.formatters.NumberBaseRoundType;
private function button_click(evt:MouseEvent):void {
textInput.errorString = "";
numberFormatter.format(textInput.text);
if (numberFormatter.error) {
textInput.errorString = numberFormatter.error;
}
arrColl = new ArrayCollection();
numberFormatter.rounding = NumberBaseRoundType.NEAREST;
arrColl.addItem({type:numberFormatter.rounding,
value:numberFormatter.format(textInput.text)});
numberFormatter.rounding = NumberBaseRoundType.UP;
arrColl.addItem({type:numberFormatter.rounding,
value:numberFormatter.format(textInput.text)});
numberFormatter.rounding = NumberBaseRoundType.DOWN;
arrColl.addItem({type:numberFormatter.rounding,
value:numberFormatter.format(textInput.text)});
numberFormatter.rounding = NumberBaseRoundType.NONE;
arrColl.addItem({type:numberFormatter.rounding,
value:numberFormatter.format(textInput.text)});
}
]]>
</mx:Script>
<mx:ArrayCollection id="arrColl" />
<mx:NumberFormatter id="numberFormatter"
precision="2"
rounding="up" />
<mx:ApplicationControlBar dock="true">
<mx:Form styleName="plain">
<mx:FormItem label="number:"
direction="horizontal">
<mx:TextInput id="textInput"
text="2.0499"
restrict="[0-9.-]"
maxChars="6" />
<mx:Button label="format"
click="button_click(event);" />
</mx:FormItem>
</mx:Form>
</mx:ApplicationControlBar>
<mx:DataGrid id="dataGrid"
dataProvider="{arrColl}"
rowCount="4" />
</mx:Application>
View source is enabled in the following example.




Very good, thank’s!