Overview | Package | Class | Use | Deprecated | Help
| GWT 2.7.0
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

## com.google.gwt.i18n.client
Class NumberFormat

    java.lang.Object
      com.google.gwt.i18n.client.NumberFormat

    public class NumberFormat

extends java.lang.Object

Formats and parses numbers using locale-sensitive patterns. This class provides comprehensive and flexible support for a wide variety of localized formats, including

- Locale-specific symbols such as decimal point, group separator, digit representation, currency symbol, percent, and permill
- Numeric variations including integers ("123"), fixed-point numbers ("123.4"), scientific notation ("1.23E4"), percentages ("12%"), and currency amounts ("$123")
- Predefined standard patterns that can be used both for parsing and formatting, including `decimal`, `currency`, `percentages`, and `scientific`
- Custom patterns and supporting features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits

### Patterns

Formatting and parsing are based on customizable patterns that can include a combination of literal characters and special characters that act as placeholders and are replaced by their localized counterparts. Many characters in a pattern are taken literally; they are matched during parsing and output unchanged during formatting. Special characters, on the other hand, stand for other characters, strings, or classes of characters. For example, the '`#`' character is replaced by a localized digit.

Often the replacement character is the same as the pattern character. In the U.S. locale, for example, the '`,`' grouping character is replaced by the same character '`,`'. However, the replacement is still actually happening, and in a different locale, the grouping character may change to a different character, such as '`.`'. Some special characters affect the behavior of the formatter by their presence. For example, if the percent character is seen, then the value is multiplied by 100 before being displayed.

The characters listed below are used in patterns. Localized symbols use the corresponding characters taken from corresponding locale symbol collection, which can be found in the properties files residing in the `com.google.gwt.i18n.client.constants`. To insert a special character in a pattern as a literal (that is, without any special meaning) the character must be quoted. There are some exceptions to this which are noted below.

Symbol | Location | Localized? | Meaning
--- | --- | --- | ---
`0` | Number | Yes | Digit
`#` | Number | Yes | Digit, zero shows as absent
`.` | Number | Yes | Decimal separator or monetary decimal separator
`-` | Number | Yes | Minus sign
`,` | Number | Yes | Grouping separator
`E` | Number | Yes | Separates mantissa and exponent in scientific notation; need not be quoted in prefix or suffix
`;` | Subpattern boundary | Yes | Separates positive and negative subpatterns
`%` | Prefix or suffix | Yes | Multiply by 100 and show as percentage
`‰` (\u2030) | Prefix or suffix | Yes | Multiply by 1000 and show as per mille
`¤` (\u00A4) | Prefix or suffix | No | Currency sign, replaced by currency symbol; if doubled, replaced by international currency symbol; if present in a pattern, the monetary decimal separator is used instead of the decimal separator
`'` | Prefix or suffix | No | Used to quote special characters in a prefix or suffix; for example, `"'#'#"` formats `123` to `"#123"`; to create a single quote itself, use two in succession, such as `"# o''clock"`

A `NumberFormat` pattern contains a postive and negative subpattern separated by a semicolon, such as `"#,##0.00;(#,##0.00)"`. Each subpattern has a prefix, a numeric part, and a suffix. If there is no explicit negative subpattern, the negative subpattern is the localized minus sign prefixed to the positive subpattern. That is, `"0.00"` alone is equivalent to `"0.00;-0.00"`. If there is an explicit negative subpattern, it serves only to specify the negative prefix and suffix; the number of digits, minimal digits, and other characteristics are ignored in the negative subpattern. That means that `"#,##0.0#;(#)"` has precisely the same result as `"#,##0.0#;(#,##0.0#)"`.

The prefixes, suffixes, and various symbols used for infinity, digits, thousands separators, decimal separators, etc. may be set to arbitrary values, and they will appear properly during formatting. However, care must be taken that the symbols and strings do not conflict, or parsing will be unreliable. For example, the decimal separator and thousands separator should be distinct characters, or parsing will be impossible.

The grouping separator is a character that separates clusters of integer digits to make large numbers more legible. It commonly used for thousands, but in some locales it separates ten-thousands. The grouping size is the number of digits between the grouping separators, such as 3 for "100,000,000" or 4 for "1 0000 0000".

### Pattern Grammar (BNF)

The pattern itself uses the following grammar:

pattern | := | subpattern ('`;`' subpattern)?
subpattern | := | prefix? number exponent? suffix?
number | := | (integer ('`.`' fraction)?) | sigDigits
prefix | := | '`\u0000`'..'`\uFFFD`' - specialCharacters
suffix | := | '`\u0000`'..'`\uFFFD`' - specialCharacters
integer | := | '`#`'* '`0`'*'`0`'
fraction | := | '`0`'* '`#`'*
sigDigits | := | '`#`'* '`@`''`@`'* '`#`'*
exponent | := | '`E`' '`+`'? '`0`'* '`0`'
padSpec | := | '`*`' padChar
padChar | := | '`\u0000`'..'`\uFFFD`' - quote

Notation:

X* | 0 or more instances of X
X? | 0 or 1 instances of X
X|Y | either X or Y
C..D | any character from C up to D, inclusive
S-T | characters in S, except those in T

The first subpattern is for positive numbers. The second (optional) subpattern is for negative numbers.

### Example

>     public class NumberFormatExample implements EntryPoint {

>       public void onModuleLoad() {
>         NumberFormat fmt = NumberFormat.getDecimalFormat();
>         double value = 12345.6789;
>         String formatted = fmt.format(value);
>         // Prints 1,2345.6789 in the default locale
>         GWT.log("Formatted string is" + formatted);

>         // Turn a string back into a double
>         value = NumberFormat.getDecimalFormat().parse("12345.6789");
>         GWT.log("Parsed value is" + value);

>         // Scientific notation
>         value = 12345.6789;
>         formatted = NumberFormat.getScientificFormat().format(value);
>         // prints 1.2345E4 in the default locale
>         GWT.log("Formatted string is" + formatted);

>         // Currency
>         fmt = NumberFormat.getCurrencyFormat();
>         formatted = fmt.format(123456.7899);
>         // prints US$123,456.79 in the default locale or $123,456.79 in the en_US
>         // locale
>         GWT.log("Formatted currency is" + formatted);

>         // Custom format
>         value = 12345.6789;
>         formatted = NumberFormat.getFormat("000000.000000").format(value);
>         // prints 012345.678900 in the default locale
>         GWT.log("Formatted string is" + formatted);
>       }
>     }

Field Summary
`protected static NumberConstants` | `defaultNumberConstants` Current NumberConstants interface to use, see `setForcedLatinDigits(boolean)` for changing it.
`protected static NumberConstants` | `localizedNumberConstants`

Constructor Summary
`protected` | `NumberFormat(NumberConstants numberConstants, java.lang.String pattern, CurrencyData cdata, boolean userSuppliedPattern)` Constructs a format object based on the specified settings.
`protected` | `NumberFormat(java.lang.String pattern, CurrencyData cdata, boolean userSuppliedPattern)` Constructs a format object for the default locale based on the specified settings.

Method Summary
`protected static NumberConstants` | `createLatinNumberConstants(NumberConstants orig)` Create a delocalized NumberConstants instance from a localized one.
`static boolean` | `forcedLatinDigits()` Returns true if all new NumberFormat instances will use latin digits and related characters rather than the localized ones.
`protected void` | `format(boolean isNegative, java.lang.StringBuilder digits, int scale)` Format a number with its significant digits already represented in string form.
`java.lang.String` | `format(double number)` This method formats a double to produce a string.
`protected java.lang.String` | `format(long value, int scale)` Format a possibly scaled long value.
`java.lang.String` | `format(java.lang.Number number)` This method formats a Number to produce a string.
`static NumberFormat` | `getCurrencyFormat()` Provides the standard currency format for the current locale.
`static NumberFormat` | `getCurrencyFormat(CurrencyData currencyData)` Provides the standard currency format for the current locale using a specified currency.
`static NumberFormat` | `getCurrencyFormat(java.lang.String currencyCode)` Provides the standard currency format for the current locale using a specified currency.
`static NumberFormat` | `getDecimalFormat()` Provides the standard decimal format for the default locale.
`static NumberFormat` | `getFormat(java.lang.String pattern)` Gets a `NumberFormat` instance for the default locale using the specified pattern and the default currencyCode.
`static NumberFormat` | `getFormat(java.lang.String pattern, CurrencyData currencyData)` Gets a custom `NumberFormat` instance for the default locale using the specified pattern and currency code.
`static NumberFormat` | `getFormat(java.lang.String pattern, java.lang.String currencyCode)` Gets a custom `NumberFormat` instance for the default locale using the specified pattern and currency code.
`static NumberFormat` | `getGlobalCurrencyFormat()` Provides the global currency format for the current locale, using its default currency.
`static NumberFormat` | `getGlobalCurrencyFormat(CurrencyData currencyData)` Provides the global currency format for the current locale, using a specified currency.
`static NumberFormat` | `getGlobalCurrencyFormat(java.lang.String currencyCode)` Provides the global currency format for the current locale, using a specified currency.
`protected int` | `getGroupingSize()` Returns the number of digits between grouping separators in the integer portion of a number.
`protected java.lang.String` | `getNegativePrefix()` Returns the prefix to use for negative values.
`protected java.lang.String` | `getNegativeSuffix()` Returns the suffix to use for negative values.
`protected NumberConstants` | `getNumberConstants()` Returns the NumberConstants instance for this formatter.
`java.lang.String` | `getPattern()` Returns the pattern used by this number format.
`static NumberFormat` | `getPercentFormat()` Provides the standard percent format for the default locale.
`protected java.lang.String` | `getPositivePrefix()` Returns the prefix to use for positive values.
`protected java.lang.String` | `getPositiveSuffix()` Returns the suffix to use for positive values.
`static NumberFormat` | `getScientificFormat()` Provides the standard scientific format for the default locale.
`static NumberFormat` | `getSimpleCurrencyFormat()` Provides the simple currency format for the current locale using its default currency.
`static NumberFormat` | `getSimpleCurrencyFormat(CurrencyData currencyData)` Provides the simple currency format for the current locale using a specified currency.
`static NumberFormat` | `getSimpleCurrencyFormat(java.lang.String currencyCode)` Provides the simple currency format for the current locale using a specified currency.
`protected boolean` | `isDecimalSeparatorAlwaysShown()` Returns true if the decimal separator should always be shown.
`NumberFormat` | `overrideFractionDigits(int digits)` Change the number of fractional digits used for formatting with this instance.
`NumberFormat` | `overrideFractionDigits(int minDigits, int maxDigits)` Change the number of fractional digits used for formatting with this instance.
`double` | `parse(java.lang.String text)` Parses text to produce a numeric value.
`double` | `parse(java.lang.String text, int[] inOutPos)` Parses text to produce a numeric value.
`protected static java.lang.String` | `remapSeparator(java.lang.String separator)` Remap a localized separator to an equivalent latin one.
`static void` | `setForcedLatinDigits(boolean useLatinDigits)` Specify whether all new NumberFormat instances will use latin digits and related characters rather than the localized ones.
`(package private) static int` | `toScaledString(java.lang.StringBuilder buf, double val)` Appends a scaled string representation to a buffer, returning the scale (which is the number of places to the right of the end of the string the decimal point should be moved -- i.e., 3.5 would be added to the buffer as "35" and a returned scale of -1).

Methods inherited from class java.lang.Object
`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

Field Detail

### localizedNumberConstants

    protected static final NumberConstants localizedNumberConstants

### defaultNumberConstants

    protected static NumberConstants defaultNumberConstants

  Current NumberConstants interface to use, see `setForcedLatinDigits(boolean)` for changing it.

Constructor Detail

### NumberFormat

    protected NumberFormat(NumberConstants numberConstants,
                           java.lang.String pattern,
                           CurrencyData cdata,
                           boolean userSuppliedPattern)

  Constructs a format object based on the specified settings.

  Parameters:
    `numberConstants` - the locale-specific number constants to use for this format -- **NOTE** subclasses passing their own instance here should pay attention to `forcedLatinDigits()` and remap localized symbols using `createLatinNumberConstants(NumberConstants)`
    `pattern` - pattern that specify how number should be formatted
    `cdata` - currency data that should be used
    `userSuppliedPattern` - true if the pattern was supplied by the user

### NumberFormat

    protected NumberFormat(java.lang.String pattern,
                           CurrencyData cdata,
                           boolean userSuppliedPattern)

  Constructs a format object for the default locale based on the specified settings.

  Parameters:
    `pattern` - pattern that specify how number should be formatted
    `cdata` - currency data that should be used
    `userSuppliedPattern` - true if the pattern was supplied by the user

Method Detail

### forcedLatinDigits

    public static boolean forcedLatinDigits()

  Returns true if all new NumberFormat instances will use latin digits and related characters rather than the localized ones.

### getCurrencyFormat

    public static NumberFormat getCurrencyFormat()

  Provides the standard currency format for the current locale.

  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the default locale

### getCurrencyFormat

    public static NumberFormat getCurrencyFormat(CurrencyData currencyData)

  Provides the standard currency format for the current locale using a specified currency.

  Parameters:
    `currencyData` - currency data to use
  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the current locale

### getCurrencyFormat

    public static NumberFormat getCurrencyFormat(java.lang.String currencyCode)

  Provides the standard currency format for the current locale using a specified currency.

  Parameters:
    `currencyCode` - valid currency code, as defined in com.google.gwt.i18n.client.constants.CurrencyCodeMapConstants.properties
  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the current locale
  Throws:
    `java.lang.IllegalArgumentException` - if the currency code is unknown

### getDecimalFormat

    public static NumberFormat getDecimalFormat()

  Provides the standard decimal format for the default locale.

  Returns:
    a `NumberFormat` capable of producing and consuming decimal format for the default locale

### getFormat

    public static NumberFormat getFormat(java.lang.String pattern)

  Gets a `NumberFormat` instance for the default locale using the specified pattern and the default currencyCode.

  Parameters:
    `pattern` - pattern for this formatter
  Returns:
    a NumberFormat instance
  Throws:
    `java.lang.IllegalArgumentException` - if the specified pattern is invalid

### getFormat

    public static NumberFormat getFormat(java.lang.String pattern,
                                         CurrencyData currencyData)

  Gets a custom `NumberFormat` instance for the default locale using the specified pattern and currency code.

  Parameters:
    `pattern` - pattern for this formatter
    `currencyData` - currency data
  Returns:
    a NumberFormat instance
  Throws:
    `java.lang.IllegalArgumentException` - if the specified pattern is invalid

### getFormat

    public static NumberFormat getFormat(java.lang.String pattern,
                                         java.lang.String currencyCode)

  Gets a custom `NumberFormat` instance for the default locale using the specified pattern and currency code.

  Parameters:
    `pattern` - pattern for this formatter
    `currencyCode` - international currency code
  Returns:
    a NumberFormat instance
  Throws:
    `java.lang.IllegalArgumentException` - if the specified pattern is invalid or the currency code is unknown

### getGlobalCurrencyFormat

    public static NumberFormat getGlobalCurrencyFormat()

  Provides the global currency format for the current locale, using its default currency.

  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the current locale

### getGlobalCurrencyFormat

    public static NumberFormat getGlobalCurrencyFormat(CurrencyData currencyData)

  Provides the global currency format for the current locale, using a specified currency.

  Parameters:
    `currencyData` - currency data to use
  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the current locale

### getGlobalCurrencyFormat

    public static NumberFormat getGlobalCurrencyFormat(java.lang.String currencyCode)

  Provides the global currency format for the current locale, using a specified currency.

  Parameters:
    `currencyCode` - valid currency code, as defined in com.google.gwt.i18n.client.constants.CurrencyCodeMapConstants.properties
  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the current locale
  Throws:
    `java.lang.IllegalArgumentException` - if the currency code is unknown

### getPercentFormat

    public static NumberFormat getPercentFormat()

  Provides the standard percent format for the default locale.

  Returns:
    a `NumberFormat` capable of producing and consuming percent format for the default locale

### getScientificFormat

    public static NumberFormat getScientificFormat()

  Provides the standard scientific format for the default locale.

  Returns:
    a `NumberFormat` capable of producing and consuming scientific format for the default locale

### getSimpleCurrencyFormat

    public static NumberFormat getSimpleCurrencyFormat()

  Provides the simple currency format for the current locale using its default currency. Note that these formats may be ambiguous if the currency isn't clear from other content on the page.

  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the current locale

### getSimpleCurrencyFormat

    public static NumberFormat getSimpleCurrencyFormat(CurrencyData currencyData)

  Provides the simple currency format for the current locale using a specified currency. Note that these formats may be ambiguous if the currency isn't clear from other content on the page.

  Parameters:
    `currencyData` - currency data to use
  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the current locale

### getSimpleCurrencyFormat

    public static NumberFormat getSimpleCurrencyFormat(java.lang.String currencyCode)

  Provides the simple currency format for the current locale using a specified currency. Note that these formats may be ambiguous if the currency isn't clear from other content on the page.

  Parameters:
    `currencyCode` - valid currency code, as defined in com.google.gwt.i18n.client .constants.CurrencyCodeMapConstants.properties
  Returns:
    a `NumberFormat` capable of producing and consuming currency format for the current locale
  Throws:
    `java.lang.IllegalArgumentException` - if the currency code is unknown

### setForcedLatinDigits

    public static void setForcedLatinDigits(boolean useLatinDigits)

  Specify whether all new NumberFormat instances will use latin digits and related characters rather than the localized ones.

  Parameters:
    `useLatinDigits` - true if latin digits/etc should be used, false if localized digits/etc should be used.

### createLatinNumberConstants

    protected static NumberConstants createLatinNumberConstants(NumberConstants orig)

  Create a delocalized NumberConstants instance from a localized one.

  Parameters:
    `orig` - localized NumberConstants instance
  Returns:
    NumberConstants instance using latin digits/etc

### remapSeparator

    protected static java.lang.String remapSeparator(java.lang.String separator)

  Remap a localized separator to an equivalent latin one.

  Parameters:
    `separator` -
  Returns:
    delocalized separator character

### toScaledString

    static int toScaledString(java.lang.StringBuilder buf,
                              double val)

  Appends a scaled string representation to a buffer, returning the scale (which is the number of places to the right of the end of the string the decimal point should be moved -- i.e., 3.5 would be added to the buffer as "35" and a returned scale of -1).

  Parameters:
    `buf` -
    `val` -
  Returns:
    scale to apply to the result

### format

    public java.lang.String format(double number)

  This method formats a double to produce a string.

  Parameters:
    `number` - The double to format
  Returns:
    the formatted number string

### format

    public java.lang.String format(java.lang.Number number)

  This method formats a Number to produce a string.

  Any `Number` which is not a `BigDecimal`, `BigInteger`, or `Long` instance is formatted as a `double` value.

  Parameters:
    `number` - The Number instance to format
  Returns:
    the formatted number string

### getPattern

    public java.lang.String getPattern()

  Returns the pattern used by this number format.

### overrideFractionDigits

    public NumberFormat overrideFractionDigits(int digits)

  Change the number of fractional digits used for formatting with this instance.

  Parameters:
    `digits` - the exact number of fractional digits for formatted values; must be >= 0
  Returns:
    `this`, for chaining purposes

### overrideFractionDigits

    public NumberFormat overrideFractionDigits(int minDigits,
                                               int maxDigits)

  Change the number of fractional digits used for formatting with this instance. Digits after `minDigits` that are zero will be omitted from the formatted value.

  Parameters:
    `minDigits` - the minimum number of fractional digits for formatted values; must be >= 0
    `maxDigits` - the maximum number of fractional digits for formatted values; must be >= `minDigits`
  Returns:
    `this`, for chaining purposes

### parse

    public double parse(java.lang.String text)
                 throws java.lang.NumberFormatException

  Parses text to produce a numeric value. A `NumberFormatException` is thrown if either the text is empty or if the parse does not consume all characters of the text.

  Parameters:
    `text` - the string being parsed
  Returns:
    a double value representing the parsed number
  Throws:
    `java.lang.NumberFormatException` - if the entire text could not be converted into a double

### parse

    public double parse(java.lang.String text,
                        int[] inOutPos)
                 throws java.lang.NumberFormatException

  Parses text to produce a numeric value.

  The method attempts to parse text starting at the index given by pos. If parsing succeeds, then the index of `pos` is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string), and the parsed number is returned. The updated `pos` can be used to indicate the starting point for the next call to this method. If an error occurs, then the index of `pos` is not changed.

  Parameters:
    `text` - the string to be parsed
    `inOutPos` - position to pass in and get back
  Returns:
    a double value representing the parsed number
  Throws:
    `java.lang.NumberFormatException` - if the text segment could not be converted into a double

### format

    protected void format(boolean isNegative,
                          java.lang.StringBuilder digits,
                          int scale)

  Format a number with its significant digits already represented in string form. This is done so both double and BigInteger/Decimal formatting can share code without requiring all users to pay the code size penalty for BigDecimal/etc.

  Example values passed in:

  - -13e2
    `isNegative=true, digits="13", scale=2`
  - 3.14158
    `isNegative=false, digits="314158", scale=-5`
  - .0001
    `isNegative=false, digits="1" ("0001" would be ok), scale=-4`

  Parameters:
    `isNegative` - true if the value to be formatted is negative
    `digits` - a StringBuilder containing just the significant digits in the value to be formatted, the formatted result will be left here
    `scale` - the number of places to the right the decimal point should be moved in the digit string -- negative means the value contains fractional digits

### format

    protected java.lang.String format(long value,
                                      int scale)

  Format a possibly scaled long value.

  Parameters:
    `value` - value to format
    `scale` - the number of places to the right the decimal point should be moved in the digit string -- negative means the value contains fractional digits
  Returns:
    formatted value

### getGroupingSize

    protected int getGroupingSize()

  Returns the number of digits between grouping separators in the integer portion of a number.

### getNegativePrefix

    protected java.lang.String getNegativePrefix()

  Returns the prefix to use for negative values.

### getNegativeSuffix

    protected java.lang.String getNegativeSuffix()

  Returns the suffix to use for negative values.

### getNumberConstants

    protected NumberConstants getNumberConstants()

  Returns the NumberConstants instance for this formatter.

### getPositivePrefix

    protected java.lang.String getPositivePrefix()

  Returns the prefix to use for positive values.

### getPositiveSuffix

    protected java.lang.String getPositiveSuffix()

  Returns the suffix to use for positive values.

### isDecimalSeparatorAlwaysShown

    protected boolean isDecimalSeparatorAlwaysShown()

  Returns true if the decimal separator should always be shown.

Overview | Package | Class | Use | Deprecated | Help
| GWT 2.7.0
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD