Formatting Data

Data formatters are user-configurable objects that format raw data into a customized string. You often use formatters with data binding to create a meaningful display of the raw data bound to a component. This can save you time by automating data formatting tasks and by letting you easily change the formatting of fields within your applications.

Using formatters

Formatters in Flex are components that you use to format data into strings. Formatters perform a one-way conversion of raw data to a formatted string. You typically trigger a formatter just before displaying data in a text field. Flex includes standard formatters that let you format currency, dates, numbers, phone numbers, and ZIP codes.

Spark and MX formatters

Flex defines two sets of formatters: Spark and MX. The Spark formatters rely on the classes in the flash.globalization package. The flash.globalization classes use the locale data provided by the operating system. Therefore, Spark formatters provide behavior that is consistent with the operating system and have access to all the locales that are supported by the operating system.

MX formatters use the Flex ResourceManager to access locale-specific data from properties files that are included in the Flex SDK. The MX formatters provide the same behavior across operating systems, but are limited to the locales provided by the Flex SDK or by the application developer.

The following table lists the Spark and MX formatting classes. When possible, it's best that you use the Spark formatters in your application:

Spark formatter

MX formatter

Description

CurrencyFormatter

CurrencyFormatter

Format a currency value.

DataTimeFormatter

DateTimeFormatter

Format a date and time value.

NumberFormatter

NumberFormatter

Format a numeric value.

PhoneFormatter

Format a phone number.

SwitchSymbolFormatter

Format a String by replacing placeholder characters in one String with numbers from a second String.

ZipCodeFormatter

Format a U.S. or Canadian postal code.

Formatter example

The following steps describe the general process for using a formatter:

  1. Declare a formatter in an <fx:Declarations> tag in your MXML code, specifying the appropriate formatting properties. You define formatters in an <fx:Declarations> tag because they are not visual components.

    You can also create formatters in ActionScript for use in an application.

  2. Call the formatter's format() method, and specify the value to be formatted as a parameter to the format() method. The format() method returns a String containing the formatted value.

The following example formats a phone number that a user inputs in an application by using the TextInput control:

<?xml version="1.0"?> 
<!-- formatters\Formatter2TextFields.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout> 
 
    <fx:Declarations> 
        <!-- Declare a PhoneFormatter and define formatting parameters.--> 
        <mx:PhoneFormatter id="phoneDisplay" 
            areaCode="415" 
            formatString="###-####" /> 
    </fx:Declarations> 
 
    <!-- Declare the input control.--> 
    <s:Label text="Enter 7 digit phone number (########):"/> 
    <s:TextInput id="myTI"/> 
    
    <!-- Declare the control to display the formatted data.--> 
    <s:TextArea text="{phoneDisplay.format(myTI.text)}"/> 
</s:Application>

In this example, you use the MX PhoneFormatter class to display the formatted phone number in a TextArea control. The format() method is called as part of a data binding expression when the text property of the TextInput control changes.

You can call the format() method from anywhere in your application, typically in response to an event. The following example declares a Spark DateTimeFormatter. The DateTimeFormatter uses the default locale-specific format for the input String. The application then writes a formatted date to the text property of a TextInput control in response to the click event of a Button control:
<?xml version="1.0" encoding="utf-8"?> 
<!-- formatters\sparkformatters\SparkFormatterDateField.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/> 
    </s:layout> 
    
    <fx:Declarations> 
        <!-- Declare a Spark DateTimeFormatter and 
             define formatting parameters.--> 
        <s:DateTimeFormatter id="dateTimeFormatter"/> 
    </fx:Declarations> 
    
    <s:Label text="Enter date (mm/dd/yyyy):"/> 
    <s:TextInput id="dob" text=""/> 
    
    <s:Label text="Formatted date: "/> 
    <s:TextInput id="formattedDate" 
        text="" width="300" 
        editable="false"/> 
    
    <!-- Format and update the date.--> 
    <s:Button label="Format Input" 
        click="formattedDate.text=dateTimeFormatter.format(dob.text);"/> 
</s:Application>

Spark formatters

Flex includes the following Spark classes for formatting dates, numbers and currencies:

The Spark formatters provide the following functionality:

  • Locale-specific formatting of dates, times, number, and currency amounts.

  • Locale-specific parsing of numbers and currency amounts.

  • Locale-specific string comparison. For more information, see Sorting and matching.

  • Locale-specific uppercase and lowercase string conversion.

The Spark formatters use the locale style property to determine how to format data based on the locale. The locale style is an inheritable style that you can set for the entire application or specifically for a particular formatter.

If a Spark formatter does not explicitly set the locale style, then it uses the value specified by the locale style of the application container. If you do not set the locale style property, the application uses the global default from the defaults.css style sheet, which defaults to en. For more information, see Setting the locale.

You can explicitly configure the formatter to use the default locale by setting the locale style to the constant value flash.globalization.LocaleID.DEFAULT.

Error handling in a Spark formatter

You call the format() method to format a value. By default, if the format() method fails, it returns null. However, you can use the errorText property of the formatter to define a String to return, as the following example shows:

<?xml version="1.0" encoding="utf-8"?> 
<!-- formatters\sparkformatters\SparkFormatterError.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/> 
    </s:layout> 
    
    <fx:Declarations> 
        <!-- Declare a Spark DateTimeFormatter and 
        define formatting parameters.--> 
        <s:DateTimeFormatter id="dateTimeFormatter" 
            dateTimePattern="month: MM, day: DD, year: YYYY" 
            errorText="Invalid input value"/> 
    </fx:Declarations> 
    
    <s:Label text="Enter date (mm/dd/yyyy):"/> 
    <s:TextInput id="dob" text=""/> 
    
    <s:Label text="Formatted date: "/> 
    <s:TextInput id="formattedDate" 
        text="" width="300" 
        editable="false"/> 
    
    <!-- Format and update the date.--> 
    <s:Button label="Format Input" 
        click="formattedDate.text=dateTimeFormatter.format(dob.text);"/> 
</s:Application>

Formatting numbers with a Spark formatter

The Spark NumberFormatter class provides basic formatting options for numeric data, including decimal formatting, thousands separator formatting, and negative sign formatting.

The format() method accepts a number or a number formatted as a String value, and returns the formatted string. When a number formatted as a String value is passed to the format() method, the function first uses the Number() function to convert the String to a Number object.

The following example uses the NumberFormatter class in an MXML file:
<?xml version="1.0" encoding="utf-8"?> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> 
    <s:layout> 
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/> 
    </s:layout> 
 
    <fx:Script> 
        <![CDATA[ 
            protected function button2_clickHandler(event:MouseEvent):void { 
                displayVal.text = PrepForDisplay.format(bigNumber.text); 
            } 
        ]]> 
    </fx:Script> 
 
    
    <fx:Declarations> 
        <!-- Declare and define parameters for the NumberFormatter.--> 
        <s:NumberFormatter id="PrepForDisplay" 
            fractionalDigits="3" 
            decimalSeparator="." 
            groupingSeparator="," 
            useGrouping="true" 
            negativeNumberFormat="0" 
            errorText="'{bigNumber.text}' is an invalid input value"/> 
    </fx:Declarations> 
    
    <!-- String to format.--> 
    <s:TextInput id="bigNumber" text="Enter number"/>  
    <s:Button label="Format Value" 
        click="button2_clickHandler(event);"/> 
    
    <!-- Display formatted value.--> 
    <s:Label id="displayVal"/> 
</s:Application>

Formatting currency with a Spark formatter

The Spark CurrencyFormatter class provides the same features as the NumberFormatter class, plus a currency symbol. It also has additional properties to control the formatted result: currencySymbol, negativeCurrencyFormat, and positiveCurrencyFormat.

The format() method accepts a Number value or a number formatted as a String value and formats the resulting string. When a number formatted as a String value is passed to the format() method, the function first uses the Number() function to convert the String to a Number object.

The useCurrencySymbol property determines the currency symbol returned in the formatted String based on the locale style property. When the useCurrencySymbol property is set to true, the formatter returns the value of the currencySymbol property in the formatted String. When the useCurrencySymbol property is set to false, the formatter returns the value of the currencyISOCode property in the formatted String.

The following example uses the CurrencyFormatter class in an MXML file:
<?xml version="1.0" encoding="utf-8"?> 
<!-- formatters\sparkformatters\SparkCurrencyFormatter.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/> 
    </s:layout> 
    
    <fx:Script> 
        <![CDATA[ 
            protected function button1_clickHandler(event:MouseEvent):void { 
                displayVal.text = Price.format(currVal.text); 
            } 
        ]]> 
    </fx:Script> 
    
    <fx:Declarations> 
        <!-- Declare a CurrencyFormatter and define parameters.--> 
        <s:CurrencyFormatter id="Price" 
            currencySymbol="$" 
            useCurrencySymbol="true" 
            negativeCurrencyFormat="0" 
            positiveCurrencyFormat="0" 
            errorText="'{currVal.text}' is an invalid input value"/> 
    </fx:Declarations> 
    
    <!-- Enter currency value, then click the Button to format. --> 
    <s:TextInput id="currVal" text="Enter value"/> 
    <s:Button label="Format Value" 
        click="button1_clickHandler(event);"/> 
 
    <!-- Display formatted value.--> 
    <s:Label id="displayVal"/> 
    
</s:Application>

Formatting dates with a Spark formatter

The Spark DateTimeFormatter class gives you a wide range of combinations for displaying date and time information. The format() method accepts a Date object, which it converts to a String based on a user-defined pattern.

The format() method can also accept a String-formatted date. If you pass a String, the formatter first converts it to a Date object by using the Date constructor. The hour value in the String must be between 0 and 23, inclusive. The minutes and seconds value must be between 0 and 59, inclusive. If the format() method is unable to parse the String into a Date object, it returns null.

The following examples show possible input strings to the format() method:

 "12/31/98" or "12-31-98" or "1998-12-31" or "12/31/1998" 
 "Friday, December 26, 2005 8:35 am" 
 "Jan. 23, 1989 11:32:25"

Using pattern strings

Use the dateTimePattern property of the DateTimeFormatter class to specify the string of pattern letters that determine the appropriate formatting. You compose a pattern string by using specific letter sequences. For example, "yyyy/MM".

Note: By omitting a pattern string, the date is formatted using the default for the current locale. By specifying a pattern string, you override the default formatting. Information, such as month and day names, are still displayed correctly for the locale, but the order of elements in the formatted string is fixed by the specified pattern string.

You can include text and punctuation in the pattern string. However the characters from "a" to "z" and from "A" to "Z" are reserved as syntax characters. Enclose these characters in single quotes to include them in the formatted output string. To include a single quote, use two single quotes. The two single quotes may appear inside or outside a quoted portion of the pattern string.

When you create a pattern string, you usually repeat pattern letters. The number of repeated letters determines the presentation. For numeric values, the number of pattern letters is the minimum number of digits; shorter numbers are zero-padded to this amount. For example, the four-letter pattern string "yyyy" corresponds to a four-digit year value.

In cases where there is a corresponding mapping of a text description—for example, the name of a month—the full form is used if the number of pattern letters is four or more; otherwise, a short or abbreviated form is used, if available. For example, if you specify the pattern string "MMMM" for month, the formatter requires the full month name, such as "December", instead of the abbreviated month name, such as "Dec".

For time values, a single pattern letter is interpreted as one or two digits. Two pattern letters are interpreted as two digits.

The complete list of options to the pattern string is defined by the setDateTimePattern() method of the flash.globalization.DateTimeFormatter class.

The following table shows sample pattern strings and the resulting presentation:

Pattern

Result

EEEE, MMMM dd, yyyy h:mm:ss a (default)

Wednesday, December 01, 2010 3:06:43 PM

yyyy.MM.dd 'at' h:mm:ss

2010.12.01 at 3:19:44

EEE, MMM d, yy

Wed, Dec 1, 10

kk 'o''clock' a

15 o'clock PM

k:mm a

12:08 PM

K:mm a

0:08 PM

yyyy.MMMM.dd HH:mm:ss

2005.July.04 12:08:34

Example: Using the Spark DateFormatter class

The following example uses the DateTimeFormatter class in an MXML file for formatting a Date object as a String:
<?xml version="1.0" encoding="utf-8"?> 
<!-- formatters\spark\SparkDateFormatter.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> 
    <s:layout> 
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/> 
    </s:layout> 
    
    <fx:Script> 
        <![CDATA[ 
            // Define variable to hold the date.        
            [Bindable] 
            private var today:Date = new Date();        
        ]]> 
    </fx:Script> 
    
    <fx:Declarations> 
        <!-- Declare a DateFormatter and define parameters.--> 
        <s:DateTimeFormatter id="DateDisplay1" 
            dateTimePattern="MMMM d, yyyy"/> 
 
        <s:DateTimeFormatter id="DateDisplay2" 
            dateTimePattern="hh:mm a"/> 
 
        <s:DateTimeFormatter id="DateDisplay3" 
            dateTimePattern="hh:mm a, MMMM d, yyyy"/> 
 
        <s:DateTimeFormatter id="DateDisplay4" 
            dateTimePattern="yyyy.MMMM.dd HH:mm:ss"/> 
</fx:Declarations> 
    
    <!-- Display the date in a Label control.--> 
    <s:Label id="myTA1" text="{DateDisplay1.format(today)}"/> 
    <!-- Display the date in a Label control.--> 
    <s:Label id="myTA2" text="{DateDisplay2.format(today)}"/> 
    <!-- Display the date in a Label control.--> 
    <s:Label id="myTA3" text="{DateDisplay3.format(today)}"/> 
    <!-- Display the date in a Label control.--> 
    <s:Label id="myTA4" text="{DateDisplay4.format(today)}"/> 
</s:Application>

MX formatters

All formatters are subclasses of the mx.formatters.Formatter class. The Formatter class declares a format() method that takes a value and returns a String value.

Writing an error handler function for an MX formatter

For most formatters, when an error occurs, the format() method returns an empty string is and a string describing the error is written to the formatter's error property. You can check for an empty string in the return value of the format() method, and if found, access the error property to determine the cause of the error.

Alternatively, you can write an error handler function that returns an error message for a formatting error. The following example shows a simple error handler function:

<?xml version="1.0"?> 
<!-- formatters\FormatterSimpleErrorForDevApps.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout> 
 
    <fx:Script> 
        <![CDATA[ 
 
            private function formatWithError(value:Object):String { 
                var formatted:String = myFormatter.format(value); 
                if (formatted == "") { 
                    if (myFormatter.error != null ) { 
                        if (myFormatter.error == "Invalid value") { 
                            formatted = ": The value is not valid."; 
                        } 
                        else { 
                            formatted = ": The formatString is not valid."; 
                        } 
                    } 
                } 
                return formatted; 
            } 
        ]]> 
    </fx:Script> 
 
    <fx:Declarations> 
        <!-- Declare a formatter and specify formatting properties.--> 
        <mx:DateFormatter id="myFormatter" 
            formatString="MXXXMXMXMXMXM"/> 
    </fx:Declarations> 
 
    <!-- Trigger the formatter while populating a string with data.--> 
    <s:TextInput id="myTI" 
        width="75%" 
        text="Your order shipped on {formatWithError('May 23, 2005')}"/> 
</s:Application>

In this example, you define a DateFormatter with an invalid format string. You then use the formatWithError() method to invoke the formatter in the TextInput control, rather than calling the Date formatter's format() method directly. In this example, if either the input string or the format string is invalid, the formatWithError() method returns an error message instead of a formatted String value.

Formatting currency with an MX formatter

The MX CurrencyFormatter class provides the same features as the NumberFormatter class, plus a currency symbol. It has two additional properties: currencySymbol and alignSymbol. (For more information about the NumberFormatter class, see Formatting numbers with an MX formatter.)

The CurrencyFormatter class provides basic formatting options for numeric data, including decimal formatting, thousands separator formatting, and negative sign formatting. The format() method accepts a Number value or a number formatted as a String value and formats the resulting string.

When a number formatted as a String is passed to the format() method, the function parses the string from left to right and attempts to extract the first sequence of numbers it encounters. The function parses the thousands separators and decimal separators along with their trailing numbers. The parser searches for a comma (,) for the thousands separator unless you set a different character in the thousandsSeparatorFrom property. The parser searches for a period (.) for the decimal separator unless you define a different character in the decimalSeparator property.

Note: When a number is provided to the format() method as a String value, a negative sign is recognized if it is a dash (-) immediately preceding the first number in the sequence. A dash, space, and then a first number are not interpreted as a negative sign.

Example: Using the MX CurrencyFormatter class

The following example uses the CurrencyFormatter class in an MXML file:

<?xml version="1.0"?> 
<!-- formatters\MainCurrencyFormatter.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout> 
 
    <fx:Script> 
        <![CDATA[ 
            // Define variable to hold the price.        
            [Bindable] 
            private var todaysPrice:Number=4025; 
        ]]> 
    </fx:Script> 
 
    <fx:Declarations> 
        <!-- Declare a CurrencyFormatter and define parameters.--> 
        <mx:CurrencyFormatter id="Price" precision="2" 
            rounding="none" 
            decimalSeparatorTo="." 
            thousandsSeparatorTo="," 
            useThousandsSeparator="true" 
            useNegativeSign="true" 
            currencySymbol="$" 
            alignSymbol="left"/> 
    </fx:Declarations> 
 
    <!-- Trigger the formatter while populating a string with data.--> 
    <s:TextInput text="Today's price is {Price.format(todaysPrice)}." 
        width="200"/> 
</s:Application>

At run time, the following text is displayed:

Today's price is $4,025.00.

Error handling: MX CurrencyFormatter class

If an error occurs, Flex returns an empty string and saves a description of the error in the error property. An error points to a problem with the value being submitted or the format string containing the user settings, as described in the following table:

Value of error property

When error occurs

Invalid value

An invalid numeric value is passed to the format() method. The value should be a valid number in the form of a Number or a String.

Invalid format

One or more of the parameters contain an unusable setting.

Formatting dates with an MX formatter

The MX DateFormatter class gives you a wide range of combinations for displaying date and time information. The format() method accepts a Date object, which it converts to a String based on a user-defined pattern. The format() method can also accept a String-formatted date, which it attempts to parse into a valid Date object prior to formatting.

The DateFormatter class has a parseDateString() method that accepts a date formatted as a String. The parseDateString() method examines sections of numbers and letters in the String to build a Date object. The parser is capable of interpreting long or abbreviated (three-character) month names, time, am and pm, and various representations of the date.

The hour value in the String must be between 0 and 23, inclusive. The minutes and seconds value must be between 0 and 59, inclusive. If the parseDateString() method is unable to parse the String into a Date object, it returns null.

The following examples show some of the ways strings can be parsed:

 "12/31/98" or "12-31-98" or "1998-12-31" or "12/31/1998" 
 "Friday, December 26, 2005 8:35 am" 
 "Jan. 23, 1989 11:32:25"

The DateFormatter class parses strings from left to right. A date value should appear before the time and must be included. The time value is optional. A time signature of 0:0:0 is the Date object's default for dates that are defined without a time. Time zone offsets are not parsed.

Using Pattern strings

You provide the DateFormatter class with a string of pattern letters, which it parses to determine the appropriate formatting. You must understand how to compose the string of pattern letters to control the formatting options and the format of the string that is returned.

You compose a pattern string by using specific uppercase letters: for example, YYYY/MM. The DateFormatter pattern string can contain other text in addition to pattern letters. To form a valid pattern string, you need only one pattern letter.

When you create a pattern string, you usually repeat pattern letters. The number of repeated letters determines the presentation. For numeric values, the number of pattern letters is the minimum number of digits; shorter numbers are zero-padded to this amount. For example, the four-letter pattern string "YYYY" corresponds to a four-digit year value.

In cases where there is a corresponding mapping of a text description—for instance, the name of a month—the full form is used if the number of pattern letters is four or more; otherwise, a short or abbreviated form is used, if available. For example, if you specify the pattern string "MMMM" for month, the formatter requires the full month name, such as "December", instead of the abbreviated month name, such as "Dec".

For time values, a single pattern letter is interpreted as one or two digits. Two pattern letters are interpreted as two digits.

The following table describes each of the available pattern letters:

Pattern letter

Description

Y

Year. If the number of pattern letters is two, the year is truncated to two digits; otherwise, it appears as four digits. The year can be zero-padded, as the third example shows in the following set of examples:

Examples:

YY = 05

YYYY = 2005

YYYYY = 02005

M

Month in year. The format depends on the following criteria:

  • If the number of pattern letters is one, the format is interpreted as numeric in one or two digits.

  • If the number of pattern letters is two, the format is interpreted as numeric in two digits.

  • If the number of pattern letters is three, the format is interpreted as short text.

  • If the number of pattern letters is four, the format is interpreted as full text.

Examples:

M = 7

MM= 07

MMM=Jul

MMMM= July

D

Day in month. While a single-letter pattern string for day is valid, you typically use a two-letter pattern string.

Examples:

D=4

DD=04

DD=10

E

Day in week. The format depends on the following criteria:

  • If the number of pattern letters is one, the format is interpreted as numeric in one or two digits.

  • If the number of pattern letters is two, the format is interpreted as numeric in two digits.

  • If the number of pattern letters is three, the format is interpreted as short text.

  • If the number of pattern letters is four, the format is interpreted as full text.

Examples:

E = 1

EE = 01

EEE = Mon

EEEE = Monday

A

am/pm indicator.

J

Hour in day (0-23).

H

Hour in day (1-24).

K

Hour in am/pm (0-11).

L

Hour in am/pm (1-12).

N

Minute in hour.

Examples:

N = 3

NN = 03

S

Second in minute.

Examples:

SS = 30

Q

Millisecond in seconds.Example:s: QQ = 78QQQ = 078

Other text

You can add other text into the pattern string to further format the string. You can use punctuation, numbers, and all lowercase letters. You should avoid uppercase letters because they may be interpreted as pattern letters.

Example:

EEEE, MMM. D, YYYY at L:NN A = Tuesday, Sept. 8, 2005 at 1:26 PM

The following table shows sample pattern strings and the resulting presentation:

Pattern

Result

YYYY.MM.DD at HH:NN:SS

2005.07.04 at 12:08:56

EEEE, MMM. D, YYYY at L:NN:QQQ A

Tuesday, Sept. 8, 2005 at 1:26:012 PM

EEE, MMM D, 'YY

Wed, Jul 4, '05

H:NN A

12:08 PM

HH o'clock A

12 o'clock PM

K:NN A

0:08 PM

YYYYY.MMMM.DD. JJ:NN A

02005.July.04. 12:08 PM

EEE, D MMM YYYY HH:NN:SS

Wed, 4 Jul 2005 12:08:56

Example: Using the DateFormatter class

The following example uses the DateFormatter class in an MXML file for formatting a Date object as a String:

<?xml version="1.0"?> 
<!-- formatters\MainDateFormatter.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout> 
 
    <fx:Script> 
        <![CDATA[ 
            // Define variable to hold the date.        
            [Bindable] 
            private var today:Date = new Date();        
        ]]> 
    </fx:Script> 
 
    <fx:Declarations> 
        <!-- Declare a DateFormatter and define parameters.--> 
        <mx:DateFormatter id="DateDisplay" 
            formatString="MMMM D, YYYY"/> 
    </fx:Declarations> 
 
    <!-- Display the date in a TextArea control.--> 
    <s:TextInput id="myTA" text="{DateDisplay.format(today)}"/> 
</s:Application>

At run time, the TextInput control displays the current date.

Error handling: DateFormatter class

If an error occurs, Flex returns an empty string and saves a description of the error in the error property. An error points to a problem with the value being submitted or the format string containing the user settings, as described in the following table:

Value of error property

When error occurs

Invalid value

A value that is not a Date object is passed to the format() method. (An empty argument is allowed.)

Invalid format
  • The formatString property is set to empty ("").

  • There is less than one pattern letter in the formatString property.

Formatting numbers with an MX formatter

The MX NumberFormatter class provides basic formatting options for numeric data, including decimal formatting, thousands separator formatting, and negative sign formatting. The format() method accepts a number or a number formatted as a String value, and formats the resulting string.

When a number formatted as a String value is passed to the format() method, the function parses the string from left to right and attempts to extract the first sequence of numbers it encounters. The function parses the thousands separators and decimal separators along with their trailing numbers. The parser searches for a comma (,) for the thousands separator unless you set a different character in the thousandsSeparatorFrom property. The parser searches for a period (.) for the decimal separator unless you define a different character in the decimalSeparator property.

Note: The format() method recognizes a dash (-) immediately preceding the first number in the sequence as a negative number. A dash, space, and then number sequence are not interpreted as a negative number.

The rounding and precision properties of the MX NumberFormatter class affect the formatting of the decimal in a number. If you use both rounding and precision properties, rounding is applied first, and then the decimal length is set by using the specified precision value. This lets you round a number and still have a trailing decimal; for example, 303.99 = 304.00.

Example: Using the MX NumberFormatter class

The following example uses the MX NumberFormatter class in an MXML file:

<?xml version="1.0"?> 
<!-- formatters\MainNumberFormatter.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout> 
 
    <fx:Script> 
        <![CDATA[ 
            // Define variable to hold the number.        
            [Bindable] 
            private var bigNumber:Number = 6000000000.65; 
        ]]> 
    </fx:Script> 
 
    <fx:Declarations> 
        <!-- Declare and define parameters for the NumberFormatter.--> 
        <mx:NumberFormatter id="PrepForDisplay" 
            precision="0" 
            rounding="up" 
            decimalSeparatorTo="." 
            thousandsSeparatorTo="," 
            useThousandsSeparator="true" 
            useNegativeSign="true"/> 
    </fx:Declarations> 
 
    <!-- Trigger the formatter while populating a string with data.--> 
    <s:TextInput text="{PrepForDisplay.format(bigNumber)}"/>  
</s:Application>

At run time, the following text appears:

6,000,000,001

Error handling: MX NumberFormatter class

If an error occurs, Flex returns an empty string and saves a description of the error in the error property. An error refers to a problem with the value being submitted or the format string that contains the user settings, as described in the following table:

Value of error property

When error occurs

Invalid value

An invalid numeric value is passed to the format() method. The value should be a valid number in the form of a Number or a String.

Invalid format

One or more of the parameters contain an unusable setting.

Formatting phone numbers with an MX formatter

The PhoneFormatter class lets you format a phone number by adjusting the format of the area code and the subscriber code. You can also adjust the country code and configuration for international formats. The value passed into the PhoneFormatter.format() method must be a Number object or a String object with only digits.

The PhoneFormatter formatString property accepts a formatted string as a definition of the format pattern. The following table shows common options for formatString values. The format() method for the PhoneFormatter accepts a sequence of numbers. The numbers correspond to the number of placeholder (#) symbols in the formatString value. The number of placeholder symbols in the formatString property and the number of digits in the format() method value must match.

formatString value

Input

Output

###-####

1234567

(xxx) 456-7890

(###) ### ####

1234567890

(123) 456-7890

###-###-####

11234567890

123-456-7890

#(###) ### ####

11234567890

1(123) 456 7890

#-###-###-####

11234567890

1-123-456-7890

+###-###-###-####

1231234567890

+123-123-456-7890

In the preceding table, dashes (-) are used as separator elements where applicable. You can substitute period (.) characters or blank spaces for the dashes. You can change the default allowable character set as needed by using the validPatternChars property. You can change the default character that represents a numeric placeholder by using the numberSymbol property (for example, to change from # to $).

Note: A shortcut is provided for the United States seven-digit format. If the areaCode property contains a value and you use the seven-digit format string, a seven-digit format entry automatically adds the area code to the string returned. The default format for the area code is (###). You can change this by using the areaCodeFormat property. You can format the area code any way you want as long as it contains three number placeholders.

Example: Using the PhoneFormatter class

The following example uses the PhoneFormatter class in an MXML file:

<?xml version="1.0"?> 
<!-- formatters\MainPhoneFormatter.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout> 
 
    <fx:Script> 
        <![CDATA[ 
            // Define variable to hold the phone number.        
            [Bindable] 
            private var newNumber:Number = 1234567; 
        ]]> 
    </fx:Script> 
 
    <fx:Declarations> 
        <!-- Declare a PhoneFormatter and define formatting parameters.--> 
        <mx:PhoneFormatter id="PhoneDisplay" 
            areaCode="415" 
            formatString="###-####"/> 
    </fx:Declarations> 
 
    <!-- Trigger the formatter while populating a string with data--> 
    <s:TextInput id="myTI" 
        initialize="myTI.text=PhoneDisplay.format(newNumber);"/> 
</s:Application>

At run time, the following text is displayed:

(415) 123-4567

Error handling: PhoneFormatter class

If an error occurs, Flex returns an empty string and saves a description of the error in the error property. An error points to a problem with the value being submitted or the format string containing the user settings, as described in the following table:

Value of error property

When error occurs

Invalid value
  • An invalid numeric value is passed to the format() method. The value should be a valid number in the form of a Number or a String.

  • The value contains a different number of digits than what is specified in the format string.

Invalid format
  • One or more of the characters in the formatString do not match the allowed characters specified in the validPatternChars property.

  • The areaCodeFormat property is specified but does not contain exactly three numeric placeholders.

Formatting zip codes with an MX formatter

The ZipCodeFormatter class lets you format five-digit or nine-digit United States ZIP codes and six-character Canadian postal codes. The ZipCodeFormatter class's formatString property accepts a formatted string as a definition of the format pattern. The formatString property is optional. If it is omitted, the default value of ##### is used.

The number of digits in the value to be formatted and the value of the formatString property must be five or nine for United States ZIP codes, and six for Canadian postal codes.

The following table shows common formatString values, input values, and output values:

formatString value

Input

Output

Format

#####

94117, 941171234

94117, 94117

Five-digit U.S. ZIP code

#####-####

941171234, 94117

94117-1234, 94117-0000

Nine-digit U.S. ZIP code

### ###

A1B2C3

A1B 2C3

Six-character Canadian postal code

For United States ZIP codes, if a nine-digit format is requested and a five-digit value is supplied, ‑0000 is appended to the value to make it compliant with the nine-digit format. Inversely, if a nine-digit value is supplied for a five-digit format, the number is truncated to five digits.

For Canadian postal codes, only a six-digit value is allowed for either the formatString or the input value.

Note: For United States ZIP codes, only numeric characters are valid. For Canadian postal codes, alphanumeric characters are allowed. Alphabetic characters must be in uppercase.

Example: Using the ZipCodeFormatter class

The following example uses the ZipCodeFormatter class in an MXML file:

<?xml version="1.0"?> 
<!-- formatters\MainZipFormatter.mxml --> 
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout> 
 
    <fx:Script> 
        <![CDATA[ 
            // Define variable to hold the ZIP code.        
            [Bindable] 
            private var storedZipCode:Number=123456789; 
        ]]> 
    </fx:Script> 
 
    <fx:Declarations> 
        <!-- Declare a ZipCodeFormatter and define parameters.--> 
        <mx:ZipCodeFormatter id="ZipCodeDisplay" 
            formatString="#####-####"/> 
    </fx:Declarations> 
 
    <!-- Trigger the formatter while populating a string with data.--> 
    <s:TextInput text="{ZipCodeDisplay.format(storedZipCode)}"/> 
</s:Application>

At run time, the following text is displayed:

12345-6789

Error handling: ZipCodeFormatter class

If an error occurs, Flex returns an empty string and saves a description of the error in the error property. An error refers to a problem with the value being submitted or the format string containing the user settings, as described in the following table:

Value of error property

When error occurs

Invalid value
  • An invalid numeric value is passed to the format() method. The value should be a valid number in the form of a Number or a String, except for Canadian postal codes, which allow alphanumeric values.

  • The number of digits does not match the allowed digits from the formatString property.

Invalid format
  • One or more of the characters in the formatString do not match the allowed characters specified in the validFormatChars property.

  • The number of numeric placeholders does not equal 9, 5, or 6.

Navigation

Using Flex » Enhancing usability

Adobe and Adobe Flash Platform are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries and are used by permission from Adobe. No other license to the Adobe trademarks are granted.