Recipe 4.5. Formatting
Numbers for Display Without a Mask
Problem
You want to format a number for display
without using a mask.
Solution
Create a NumberFormat object with no mask
setting, then call the format( ) method.
Discussion
Recipe
4.4 discusses complex ways to format numbers as strings,
including using masks and applying leading and trailing zeros and
spaces. Sometimes, however, you just want to format a number
without those complexities. The NumberFormat class provides
that simplicity as well. If no mask is applied to a
NumberFormat object, then the format( ) method
applies basic, localized formatting to a number, as shown in the
following example:
var styler:NumberFormat = new NumberFormat( );
trace(styler.format(12.3));
trace(styler.format(123.4));
trace(styler.format(1234.5));
trace(styler.format(12345.6));
Notice that a mask wasn't applied to the
NumberFormat object at any point. Assuming U.S.-style
formatting, the preceding code outputs the following:
12.3
123.4
1,234.5
12,345.6
As with the other use of the format( ) method (discussed in
Recipe
4.4), this usage attempts to use automatic localization
detection. However, the same issues may be applicable. You may
prefer to override the automatic localization settings, and you can
accomplish that by using the same techniques discussed in Recipe
4.4, as illustrated with the following example:
var styler:NumberFormat = new NumberFormat( );
Locale.slanguage = "fr";
trace(styler.format(1234, new Locale("en")));
trace(styler.format(12345, {group: ":", decimal: "|"}));
trace(styler.format(123456));
The output from the preceding code is as
follows:
1,234
12:345
123.456
See Also
Recipes 4.3
and 4.4
can be used to ensure a certain number of digits are displayed past
the decimal point. Then aligning numbers is simply a matter of
setting the text field's format to right justification using the
TextFormat .align property. Also refer to
Recipe
4.6.
|