Top Description Inners Fields Constructors Methods
com.ibm.icu.text

public abstract Class NumberFormat

extends UFormat
Class Inheritance
Known Direct Subclasses
com.ibm.icu.impl.DateNumberFormat, com.ibm.icu.text.RuleBasedNumberFormat, com.ibm.icu.text.DecimalFormat
Imports
java.io.IOException, .InvalidObjectException, .ObjectInputStream, .ObjectOutputStream, java.math.BigInteger, java.text.FieldPosition, .Format, .ParseException, .ParsePosition, java.util.Collections, .Locale, .MissingResourceException, .Set, com.ibm.icu.impl.ICUData, .ICUResourceBundle, com.ibm.icu.number.NumberFormatter, com.ibm.icu.util.Currency, .Currency.CurrencyUsage, .CurrencyAmount, .ULocale, .ULocale.Category, .UResourceBundle

ICU Enhancement

This class is ICU's replacement for java.text.NumberFormat.

ICU

Methods, fields, and other functionality specific to ICU are labeled 'ICU'.

Important Note

New users are strongly encouraged to see if NumberFormatter fits their use case. Although not deprecated, this class, NumberFormat, is only provided for java.text.NumberFormat compatibility.


NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are. NumberFormat helps you to format and parse numbers for any locale. Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.

To format a number for the current Locale, use one of the factory class methods:

 myString = NumberFormat.getInstance().format(myNumber);
If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
NumberFormat nf = NumberFormat.getInstance();
for (int i = 0; i < a.length; ++i) {
    output.println(nf.format(myNumber[i]) + "; ");
}
To format a number for a different Locale, specify it in the call to getInstance.
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
You can also use a NumberFormat to parse numbers:
myNumber = nf.parse(myString);
Use getInstance or getNumberInstance to get the normal number format. Use getIntegerInstance to get an integer number format. Use getCurrencyInstance to get the currency number format. And use getPercentInstance to get a format for displaying percentages. Some factory methods are found within subclasses of NumberFormat. With this format, a fraction like 0.53 is displayed as 53%.

Starting from ICU 4.2, you can use getInstance() by passing in a 'style' as parameter to get the correct instance. For example, use getInstance(...NUMBERSTYLE) to get the normal number format, getInstance(...PERCENTSTYLE) to get a format for displaying percentage, getInstance(...SCIENTIFICSTYLE) to get a format for displaying scientific number, getInstance(...INTEGERSTYLE) to get an integer number format, getInstance(...CURRENCYSTYLE) to get the currency number format, in which the currency is represented by its symbol, for example, "$3.00". getInstance(...ISOCURRENCYSTYLE) to get the currency number format, in which the currency is represented by its ISO code, for example "USD3.00". getInstance(...PLURALCURRENCYSTYLE) to get the currency number format, in which the currency is represented by its full name in plural format, for example, "3.00 US dollars" or "1.00 US dollar".

You can also control the display of numbers with such methods as setMinimumFractionDigits. If you want even more control over the format or parsing, or want to give your users more control, you can try casting the NumberFormat you get from the factory methods to a DecimalFormat. This will work for the vast majority of locales; just remember to put it in a try block in case you encounter an unusual one.

NumberFormat is designed such that some controls work for formatting and others work for parsing. The following is the detailed description for each these control methods,

setParseIntegerOnly : only affects parsing, e.g. if true, "3456.78" -> 3456 (and leaves the parse position just after '6') if false, "3456.78" -> 3456.78 (and leaves the parse position just after '8') This is independent of formatting. If you want to not show a decimal point where there might be no digits after the decimal point, use setDecimalSeparatorAlwaysShown on DecimalFormat.

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to:

For example, you can align numbers in two ways:
  1. If you are using a monospaced font with spacing for alignment, you can pass the FieldPosition in your format call, with field = INTEGER_FIELD. On output, getEndIndex will be set to the offset between the last character of the integer and the decimal. Add (desiredSpaceCount - getEndIndex) spaces at the front of the string.
  2. If you are using proportional fonts, instead of padding with spaces, measure the width of the string in pixels from the start to getEndIndex. Then move the pen by (desiredPixelWidth - widthToAlignmentPoint) before drawing the text. It also works where there is no decimal, but possibly additional characters at the end, e.g., with parentheses in negative numbers: "(12)" for -12.

Synchronization

Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

DecimalFormat

DecimalFormat is the concrete implementation of NumberFormat, and the NumberFormat API is essentially an abstraction from DecimalFormat's API. Refer to DecimalFormat for more information about this API.

see DecimalFormat see java.text.ChoiceFormat
Authors
Mark Davis, Helena Shih, Alan Liu
ICU Status
Stable since ICU 2.0.

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
NumberFormat.Field

The instances of this inner class are used as attribute keys and values in AttributedCharacterIterator that NumberFormat.formatToCharacterIterator() method returns.

public abstract static class
NumberFormat.NumberFormatFactory

A NumberFormatFactory is used to register new number formats.

pack-priv abstract static class
public abstract static class
NumberFormat.SimpleNumberFormatFactory

A NumberFormatFactory that supports a single locale.

Field Summary

Modifier and TypeField and Description
public static final int
private DisplayContext
public static final int
private Currency
currency

Currency object used to format currencies.

public static final int
pack-priv static final int
private static final char[]
private static final String
public static final int
FRACTION_FIELD

Field constant used to construct a FieldPosition object.

private boolean
groupingUsed

True if the the grouping (i.e. thousands) separator is used when formatting and parsing numbers.

public static final int
INTEGER_FIELD

Field constant used to construct a FieldPosition object.

public static final int
public static final int
private byte
maxFractionDigits

The maximum number of digits allowed in the fractional portion of a number.

private int
maximumFractionDigits

The maximum number of digits allowed in the fractional portion of a number.

private int
maximumIntegerDigits

The maximum number of digits allowed in the integer portion of a number.

private byte
maxIntegerDigits

The maximum number of digits allowed in the integer portion of a number.

private byte
minFractionDigits

The minimum number of digits allowed in the fractional portion of a number.

private int
minimumFractionDigits

The minimum number of digits allowed in the fractional portion of a number.

private int
minimumIntegerDigits

The minimum number of digits allowed in the integer portion of a number.

private byte
minIntegerDigits

The minimum number of digits allowed in the integer portion of a number.

public static final int
private boolean
parseIntegerOnly

True if this format will parse numbers as integers only.

private boolean
public static final int
public static final int
public static final int
private int
serialVersionOnStream

Describes the version of NumberFormat present on the stream.

private static final long
private static NumberFormat.NumberFormatShim
public static final int

Constructor Summary

AccessConstructor and Description
public
NumberFormat()

Empty constructor.

Method Summary

Modifier and TypeMethod and Description
public Object
clone()

Overrides java.text.Format.clone.

Overrides clone.
pack-priv static NumberFormat
createInstance(ULocale desiredLocale, int choice)

public boolean

Returns:

true if the object is equal to this.
equals
(Object
the object to compare against
obj
)

Overrides java.lang.Object.equals.

Overrides equals.
public StringBuffer
format(Object
The object to format
number
,
StringBuffer
where the text is to be appended
toAppendTo
,
FieldPosition
A FieldPosition identifying a field in the formatted text
pos
)

Implements abstract java.text.Format.format.

Formats a number and appends the resulting text to the given string buffer.
public final String
format(double number)

Specialization of format.

public final String
format(long number)

Specialization of format.

public final String
format(BigInteger number)

ICU

public final String
format(BigDecimal number)

Convenience method to format a BigDecimal.

public final String
format(BigDecimal number)

ICU

public final String
format(CurrencyAmount currAmt)

ICU

public abstract StringBuffer
format(double number, StringBuffer toAppendTo, FieldPosition pos)

Specialization of format.

public abstract StringBuffer
format(long number, StringBuffer toAppendTo, FieldPosition pos)

Specialization of format.

public abstract StringBuffer
format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos)

ICU

public abstract StringBuffer
format(BigDecimal number, StringBuffer toAppendTo, FieldPosition pos)

ICU

public abstract StringBuffer
format(BigDecimal number, StringBuffer toAppendTo, FieldPosition pos)

ICU

public StringBuffer
format(CurrencyAmount currAmt, StringBuffer toAppendTo, FieldPosition pos)

ICU

public static Locale[]

Returns:

the available locales
getAvailableLocales
()

Returns the list of Locales for which NumberFormats are available.

public static ULocale[]

Returns:

the available locales
getAvailableULocales
()

ICU

public DisplayContext

Returns:

the current DisplayContext setting for the specified type
getContext
(DisplayContext.Type
the DisplayContext.Type whose value to return
type
)

ICU

public Currency
getCurrency()

Returns the Currency object used to display currency amounts.

public static final NumberFormat

Returns:

a number format for currency
getCurrencyInstance
()

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat

Returns:

a number format for currency
getCurrencyInstance
(Locale inLocale)

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat

Returns:

a number format for currency
getCurrencyInstance
(ULocale inLocale)

ICU

protected Currency

Returns:

a non-null Currency
getEffectiveCurrency
()

Deprecated This API is ICU internal only.
Returns the currency in effect for this formatter.
public static final NumberFormat
getInstance()

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat
getInstance(Locale inLocale)

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat
getInstance(ULocale inLocale)

ICU

public static final NumberFormat
getInstance(int
number format style
style
)

ICU

public static NumberFormat
getInstance(Locale
the specific locale.
inLocale
,
int
number format style
style
)

ICU

public static NumberFormat
getInstance(ULocale
the specific locale.
desiredLocale
,
int
number format style
choice
)

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static final NumberFormat

Returns:

a number format for integer values
getIntegerInstance
()

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat

Returns:

a number format for integer values
getIntegerInstance
(Locale
the locale for which a number format is needed
inLocale
)

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat

Returns:

a number format for integer values
getIntegerInstance
(ULocale
the locale for which a number format is needed
inLocale
)

ICU

public int

Returns:

the maximum number of fraction digits
getMaximumFractionDigits
()

Returns the maximum number of digits allowed in the fraction portion of a number.

public int

Returns:

the maximum number of integer digits
getMaximumIntegerDigits
()

Returns the maximum number of digits allowed in the integer portion of a number.

public int

Returns:

the minimum number of fraction digits
getMinimumFractionDigits
()

Returns the minimum number of digits allowed in the fraction portion of a number.

public int

Returns:

the minimum number of integer digits
getMinimumIntegerDigits
()

Returns the minimum number of digits allowed in the integer portion of a number.

public static final NumberFormat
getNumberInstance()

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat
getNumberInstance(Locale inLocale)

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat
getNumberInstance(ULocale inLocale)

ICU

protected static String

Returns:

the pattern
getPattern
(Locale
the locale of the data.
forLocale
,
int
the pattern format.
choice
)

Deprecated ICU 3.4 subclassers should override getPattern(ULocale, int) instead of this method.
Returns the pattern for the provided locale and choice.
protected static String

Returns:

the pattern
getPattern
(ULocale
the locale of the data.
forLocale
,
int
the pattern format.
choice
)

Returns the pattern for the provided locale and choice.

public static String

Returns:

the pattern
getPatternForStyle
(ULocale
the locale of the data.
forLocale
,
int
the pattern format.
choice
)

Deprecated This API is ICU internal only.
Returns the pattern for the provided locale and choice.
public static String

Returns:

the pattern
getPatternForStyleAndNumberingSystem
(ULocale
the locale of the data.
forLocale
,
String
The name of the numbering system, like "latn".
nsName
,
int
the pattern format.
choice
)

Deprecated This API is ICU internal only.
Returns the pattern for the provided locale, numbering system, and choice.
public static final NumberFormat

Returns:

a number format for percents
getPercentInstance
()

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat

Returns:

a number format for percents
getPercentInstance
(Locale inLocale)

Note

New users are strongly encouraged to use NumberFormatter instead of NumberFormat.

public static NumberFormat

Returns:

a number format for percents
getPercentInstance
(ULocale inLocale)

ICU

public int

Returns:

A rounding mode, between BigDecimal.ROUND_UP and BigDecimal.ROUND_UNNECESSARY.
getRoundingMode
()

Returns the rounding mode used in this NumberFormat.

public static final NumberFormat

Returns:

a scientific number format
getScientificInstance
()

ICU

public static NumberFormat

Returns:

a scientific number format
getScientificInstance
(Locale inLocale)

ICU

public static NumberFormat

Returns:

a scientific number format
getScientificInstance
(ULocale inLocale)

ICU

private static NumberFormat.NumberFormatShim
public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for the object.
public boolean

Returns:

true if grouping is used
isGroupingUsed
()

Returns true if grouping is used in this format.

public boolean

Returns:

true if this will parse integers only
isParseIntegerOnly
()

Returns true if this format will parse numbers as integers only.

public boolean

Returns:

true if strict parsing is in effect
isParseStrict
()

ICU

public abstract Number
parse(String text, ParsePosition parsePosition)

Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals); otherwise, returns another type, such as a BigDecimal, BigInteger, or Double.

public Number

Returns:

A Number parsed from the string.
parse
(String
A String whose beginning should be parsed.
text
)

Parses text from the beginning of the given string to produce a number.

public CurrencyAmount

Returns:

a CurrencyAmount, or null upon failure
parseCurrency
(CharSequence
the text to parse
text
,
ParsePosition
input-output position; on input, the position within text to match; must have 0 <= pos.getIndex() < text.length(); on output, the position after the last matched character. If the parse fails, the position in unchanged upon output.
pos
)

Parses text from the given string as a CurrencyAmount.

public final Object

Returns:

the parsed number, or null
parseObject
(String
the String to parse
source
,
ParsePosition
the position at which to start the parse
parsePosition
)

Implements abstract java.text.Format.parseObject.

Parses text from a string to produce a number.
private void
readObject(ObjectInputStream stream)

First, read in the default serializable data.

public static Object

Returns:

a key with which to unregister the factory
registerFactory
(NumberFormat.NumberFormatFactory
the factory to register
factory
)

ICU

public void
setContext(DisplayContext
The DisplayContext value to set.
context
)

ICU

public void
setCurrency(Currency
new currency object to use. May be null for some subclasses.
theCurrency
)

Sets the Currency object used to display currency amounts.

public void
setGroupingUsed(boolean
true to use grouping.
newValue
)

Sets whether or not grouping will be used in this format.

public void
setMaximumFractionDigits(int
the maximum number of fraction digits to be shown; if less than zero, then zero is used. The concrete subclass may enforce an upper limit to this value appropriate to the numeric type being formatted.
newValue
)

Sets the maximum number of digits allowed in the fraction portion of a number.

public void
setMaximumIntegerDigits(int
the maximum number of integer digits to be shown; if less than zero, then zero is used. Subclasses might enforce an upper limit to this value appropriate to the numeric type being formatted.
newValue
)

Sets the maximum number of digits allowed in the integer portion of a number.

public void
setMinimumFractionDigits(int
the minimum number of fraction digits to be shown; if less than zero, then zero is used. Subclasses might enforce an upper limit to this value appropriate to the numeric type being formatted.
newValue
)

Sets the minimum number of digits allowed in the fraction portion of a number.

public void
setMinimumIntegerDigits(int
the minimum number of integer digits to be shown; if less than zero, then zero is used. Subclasses might enforce an upper limit to this value appropriate to the numeric type being formatted.
newValue
)

Sets the minimum number of digits allowed in the integer portion of a number.

public void
setParseIntegerOnly(boolean
true if this should parse integers only
value
)

Sets whether to ignore the fraction part of a number when parsing (defaults to false).

public void
setParseStrict(boolean
True to enable strict parsing. Default is false.
value
)

ICU

public void
setRoundingMode(int
A rounding mode, between BigDecimal.ROUND_UP and BigDecimal.ROUND_UNNECESSARY.
roundingMode
)

Set the rounding mode used in this NumberFormat.

public static boolean

Returns:

true if the object was successfully unregistered
unregister
(Object
a key obtained from registerFactory
registryKey
)

ICU

private void
writeObject(ObjectOutputStream stream)

Write out the default serializable data, after first setting the byte fields such as maxIntegerDigits to be equal to the int fields such as maximumIntegerDigits (or to Byte.MAX_VALUE, whichever is smaller), for compatibility with the JDK 1.1 version of the stream format.

Inherited from com.ibm.icu.text.UFormat:
getLocalesetLocale