The NumberFormatter class formats numeric values (of type
int, uint, or Number) according to the conventions of a specific
locale.
The following example shows the simplest way to format a number
using the default formatting properties provided by the user’s operating
system:
var nf:NumberFormatter = new NumberFormatter(LocaleID.DEFAULT);
trace(nf.formatNumber(-123456.789))
The result vary based on the user’s locale settings and user
preferences. For example, if the user’s locale is fr-FR then the
formatted value would be:
-123.456,789
If you only want to format a number for a specific locale, regardless
of the user’s settings, set the locale name specifically. For example:
var nf:NumberFormatter = new NumberFormatter("de-CH");
trace(nf.formatNumber(-123456.789));
The result in this case are:
-123'456.789
The formatNumber() method takes a Number as a parameter. The
NumberFormatter class also has a formatInt() method that takes an
int as input, and a formatUint() method that takes a uint.
You can explicitly control the formatting logic by setting properties
of the NumberFormatter class, as shown in this example:
var nf:NumberFormatter = new NumberFormatter("de-CH");
nf.negativeNumberFormat = 0;
nf.fractionalDigits = 5;
nf.trailingZeros = true;
nf.decimalSeparator = ",";
nf.useGrouping = false;
trace(nf.formatNumber(-123456.789)); //(123456.78900)
This example first creates a NumberFormatter object and then:
-
sets the negative number format to use parentheses (as
in financial applications);
-
sets the number of digits after the decimal separator to
5;
-
specifies that trailing zeroes be used to ensure five decimal
places;
-
sets the decimal separator to a comma;
-
tells the formatter not to use any grouping separators.
Note:
When some of these properties change, the resulting number
format no longer corresponds to the preferred format for the specified
locale. Use some of these properties only when locale-awareness
is not important; when you need detailed control over a single aspect
of the format, such as the number of trailing zeroes; or when the
user requests the change directly, for example, through the Windows Control
Panel.