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.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/12/13/rounding-numbers-in-flex-using-the-numberformatter-class/ -->
<mx:Application name="NumberFormatter_rounding_test"
        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.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

9 Responses to Rounding numbers in Flex using the NumberFormatter class

  1. Lucas says:

    Very good, thank’s!

  2. Hervé says:

    restrict=”[0-9.-]”

    would be :

    restrict=”[0-9.\-]” in mxml
    and
    restrict=”[0-9.\\-]” in actionscript

  3. Molaro says:

    So, I am having a rounding issue and this app is helping me sort of confirm the issue. Can you explain why if I put it:
    45.68 the rounding UP value is 45.68 (and not 45.69)

    If I put in 17.76 (my problem number in my personal app), the round UP is 17.77 (and not 17.76 like the first example)

    Overall, with a precision of 2, and rounding up, all my numbers in my app round like the first example, 45.68, however 17.76 actually rounds up. Can you explain this??? (Flex 3.5)

    • Peter deHaan says:

      @Molaro,

      This is just a guess, but sometimes JavaScript/ActionScript and many other languages store seemingly simple values like “17.76″ internally as “17.760000000000005″. So this may be an artifact of the floating point math. So your value of 17.76 has that trailing “0000000000005″ which is causing it to get rounded up.

      But again, this is just a guess and I could be very wrong. But for a bit more info on my theory, see http://stackoverflow.com/questions/588004/is-javascripts-math-broken

      Peter

  4. Molaro says:

    Peter, thanks for the reply. I have seen that before and usually if I trace out the division of the 2 numbers I use to get that number (17.76), I can see that longer value. But in this case I have littler just keyed in the number into my own test code as well as your demo and see the same issue. I’ll keep looking.

    I logged this as a possible bug with Adobe hoping they can provide an explanation if it isn’t a bug.

    Honestly, given that it 17.76, the year of our independence, I sort of assumed some odd developer bug/Easter egg!

  5. I am looking a textInput Field in which I can restrict first three numaric values and further three alphabet in maxChar 6.
    Please send me a solution.

    Thanks In Advance.
    M.Imran
    0092-321-602-8608

  6. Al says:

    So, given a NumberFormatter with these settings:
    decimalSeparatorTo=”.”
    rounding=”nearest”
    precision=”2″
    useThousandsSeparator=”false”

    Why do these numbers round to .51 as intended:
    [Bindable]
    private var numString1:String = “5.5050″;
    [Bindable]
    private var numString2:String = “85.5050″;
    [Bindable]
    private var numString3:String = “485.5050″;

    But this number rounds incorrectly to .50 ???
    [Bindable]
    private var numString4:String = “8485.5050″;

    More importantly, how does one work around this, when the popular *1000 / 1000 trick doesn’t seem to work?

  7. ejiro says:

    How can I zerofill an output result, integer ?

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree