APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.text

public abstract Class NumberFormat

extends Format
Class Inheritance
Known Direct Subclasses
java.text.ChoiceFormat, java.text.CompactNumberFormat, java.text.DecimalFormat
Imports
java.io.IOException, .InvalidObjectException, .ObjectInputStream, .ObjectOutputStream, java.math.BigInteger, .RoundingMode, java.text.spi.NumberFormatProvider, java.util.Currency, .HashMap, .Locale, .Map, .Objects, java.util.concurrent.atomic.AtomicInteger, .AtomicLong, sun.util.locale.provider.LocaleProviderAdapter, .LocaleServiceProviderPool

NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers in a localized manner. This enables code that can be completely independent of the locale conventions for decimal points, thousands-separators, the particular decimal digits used, or whether the number format is even decimal. For example, this class could be used within an application to produce a number in a currency format according to the conventions of the desired locale.

Getting a NumberFormat

To get a NumberFormat for the default Locale, use one of the static factory methods that return a concrete subclass of NumberFormat. The following formats all provide an example of formatting the Number "2000.50" with the US locale as the default locale. Alternatively, if a NumberFormat for a different locale is required, use one of the overloaded factory methods that take Locale as a parameter, for example, getIntegerInstance(Locale). If the installed locale-sensitive service implementation does not support the given Locale, the parent locale chain will be looked up, and a Locale used that is supported.

Locale Extensions

Formatting behavior can be changed when using a locale that contains any of the following Unicode extensions,

For both "nu" and "cu", if they are specified in addition to "rg", the respective values from the "nu" and "cu" extension supersede the implicit ones from the "rg" extension. Although Unicode extensions defines various keys and values, actual locale-sensitive service implementations in a Java Runtime Environment might not support any particular Unicode locale attributes or key/type pairs.

Below is an example of a "US" locale currency format with accounting style,

NumberFormat.getCurrencyInstance(Locale.forLanguageTag("en-US-u-cf-account"));
With this style, a negative value is formatted enclosed in parentheses, instead of being prepended with a minus sign.

Using NumberFormat

The following is an example of formatting and parsing in a localized fashion,
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US); currencyFormat.format(100000); // returns "$100,000.00" currencyFormat.parse("$100,000.00"); // returns 100000
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
currencyFormat.format(100000); // returns "$100,000.00"
currencyFormat.parse("$100,000.00"); // returns 100000

Customizing NumberFormat

NumberFormat provides API to customize formatting and parsing behavior,

To provide more control over formatting or parsing behavior, type checking can be done to safely convert to an implementing subclass of NumberFormat; this provides additional methods defined by the subclass. For example,

NumberFormat nFmt = NumberFormat.getInstance(Locale.US); if (nFmt instanceof DecimalFormat dFmt) { dFmt.setDecimalSeparatorAlwaysShown(true); dFmt.format(100); // returns "100." }
NumberFormat nFmt = NumberFormat.getInstance(Locale.US);
if (nFmt instanceof DecimalFormat dFmt) {
    dFmt.setDecimalSeparatorAlwaysShown(true);
    dFmt.format(100); // returns "100."
}
The NumberFormat subclass returned by the factory methods is dependent on the locale-service provider implementation installed, and may not always be DecimalFormat or CompactNumberFormat.

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.

Leniency

NumberFormat by default, parses leniently. Subclasses may consider implementing strict parsing and as such, overriding and providing implementations for the optional isStrict() and setStrict(boolean) methods.

Lenient parsing should be used when attempting to parse a number out of a String that contains non-numerical or non-format related values. For example, using a Locale#US currency format to parse the number 1000 out of the String "$1,000.00 was paid". Lenient parsing also allows loose matching of characters in the source text. For example, an implementation of the NumberFormat class may allow matching "−" (U+2212 MINUS SIGN) to the "-" (U+002D HYPHEN-MINUS) pattern character when used as a negative prefix.

Strict parsing should be used when attempting to ensure a String adheres exactly to a locale's conventions, and can thus serve to validate input. For example, successfully parsing the number 1000.55 out of the String "1.000,55" confirms the String exactly adhered to the Locale#GERMANY numerical conventions.

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.

Implementation Specification

Null Parameter Handling

Default RoundingMode
Authors
Mark Davis, Helena Shih
Since
1.1
External Specification
https://www.unicode.org/reports/tr35
See Also
DecimalFormat, ChoiceFormat, CompactNumberFormat, Locale

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
NumberFormat.Field

Defines constants that are used as attribute keys in the AttributedCharacterIterator returned from NumberFormat.formatToCharacterIterator and as field identifiers in FieldPosition.

public static enum
NumberFormat.Style

A number format style.

Field Summary

Modifier and TypeField and Description
private static final int
private static final int
pack-priv static final int
public static final int
FRACTION_FIELD

Field constant used to construct a FieldPosition object.

private boolean
groupingUsed

True if 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.

private 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.

private static final int
private boolean
parseIntegerOnly

True if this format will parse numbers as integers only.

private static final int
private static final int
private int
serialVersionOnStream

Describes the version of NumberFormat present on the stream.

pack-priv static final long

Constructor Summary

AccessConstructor and Description
protected
NumberFormat()

Sole constructor.

Method Summary

Modifier and TypeMethod and Description
public Object
clone()

Overrides java.text.Format.clone.

Overrides Cloneable.

public boolean

Returns:

true if the specified object is equal to this NumberFormat
equals
(Object
object to be compared for equality
obj
)

Overrides java.lang.Object.equals.

Compares the specified object with this NumberFormat for equality.

pack-priv String
fastFormat(double number)

public StringBuffer

Returns:

the value passed in as toAppendTo
format
(Object
the number to format
number
,
StringBuffer
the StringBuffer to which the formatted text is to be appended
toAppendTo
,
FieldPosition
keeps track on the position of the field within the returned string. For example, for formatting a number 1234567.89 in Locale.US locale, if the given fieldPosition is NumberFormat#INTEGER_FIELD, the begin index and end index of fieldPosition will be set to 0 and 9, respectively for the output string 1,234,567.89.
pos
)

Implements abstract java.text.Format.format.

Formats a number and appends the resulting text to the given string buffer.

pack-priv Format.StringBuf
public final String

Returns:

the formatted String
format
(double
the double number to format
number
)

Specialization of format.

public final String

Returns:

the formatted String
format
(long
the long number to format
number
)

Specialization of format.

public abstract StringBuffer

Returns:

the formatted StringBuffer
format
(double
the double number to format
number
,
StringBuffer
the StringBuffer to which the formatted text is to be appended
toAppendTo
,
FieldPosition
keeps track on the position of the field within the returned string. For example, for formatting a number 1234567.89 in Locale.US locale, if the given fieldPosition is NumberFormat#INTEGER_FIELD, the begin index and end index of fieldPosition will be set to 0 and 9, respectively for the output string 1,234,567.89.
pos
)

Specialization of format.

pack-priv Format.StringBuf
format(double number, Format.StringBuf toAppendTo, FieldPosition pos)

public abstract StringBuffer

Returns:

the formatted StringBuffer
format
(long
the long number to format
number
,
StringBuffer
the StringBuffer to which the formatted text is to be appended
toAppendTo
,
FieldPosition
keeps track on the position of the field within the returned string. For example, for formatting a number 123456789 in Locale.US locale, if the given fieldPosition is NumberFormat#INTEGER_FIELD, the begin index and end index of fieldPosition will be set to 0 and 11, respectively for the output string 123,456,789.
pos
)

Specialization of format.

pack-priv Format.StringBuf
format(long number, Format.StringBuf toAppendTo, FieldPosition pos)

public static Locale[]

Returns:

An array of locales for which localized NumberFormat instances are available.
getAvailableLocales
()

Returns an array of all locales for which the get*Instance methods of this class can return localized instances.

public static NumberFormat

Returns:

A NumberFormat instance for compact number formatting
getCompactNumberInstance
()

Returns a compact number format for the default FORMAT locale with "SHORT" format style.

public static NumberFormat

Returns:

A NumberFormat instance for compact number formatting
getCompactNumberInstance
(Locale
the desired locale
locale
,
NumberFormat.Style
the style for formatting a number
formatStyle
)

Returns a compact number format for the specified locale and formatStyle.

public Currency

Returns:

the currency used by this number format, or null
getCurrency
()

Gets the currency used by this number format when formatting currency values.

public static final NumberFormat

Returns:

the NumberFormat instance for currency formatting
getCurrencyInstance
()

Returns a currency format for the current default FORMAT locale.

public static NumberFormat

Returns:

the NumberFormat instance for currency formatting
getCurrencyInstance
(Locale
the desired locale
inLocale
)

Returns a currency format for the specified locale.

public static final NumberFormat

Returns:

the NumberFormat instance for general-purpose number formatting
getInstance
()

Returns a general-purpose number format for the current default FORMAT locale.

public static NumberFormat

Returns:

the NumberFormat instance for general-purpose number formatting
getInstance
(Locale
the desired locale
inLocale
)

Returns a general-purpose number format for the specified locale.

private static NumberFormat
getInstance(Locale desiredLocale, NumberFormat.Style formatStyle, int choice)

private static NumberFormat
getInstance(LocaleProviderAdapter adapter, Locale locale, NumberFormat.Style formatStyle, int choice)

public static final NumberFormat

Returns:

a number format for integer values
getIntegerInstance
()

Returns an integer number format for the current default FORMAT locale.

public static NumberFormat

Returns:

a number format for integer values
getIntegerInstance
(Locale
the desired locale
inLocale
)

Returns an integer number format for the specified locale.

public int

Returns:

the maximum number of digits.
getMaximumFractionDigits
()

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

public int

Returns:

the maximum number of digits
getMaximumIntegerDigits
()

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

public int

Returns:

the minimum number of digits
getMinimumFractionDigits
()

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

public int

Returns:

the minimum number of digits
getMinimumIntegerDigits
()

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

public static final NumberFormat

Returns:

the NumberFormat instance for general-purpose number formatting
getNumberInstance
()

Returns a general-purpose number format for the current default FORMAT locale.

public static NumberFormat

Returns:

the NumberFormat instance for general-purpose number formatting
getNumberInstance
(Locale
the desired locale
inLocale
)

Returns a general-purpose number format for the specified locale.

public static final NumberFormat

Returns:

the NumberFormat instance for percentage formatting
getPercentInstance
()

Returns a percentage format for the current default FORMAT locale.

public static NumberFormat

Returns:

the NumberFormat instance for percentage formatting
getPercentInstance
(Locale
the desired locale
inLocale
)

Returns a percentage format for the specified locale.

public RoundingMode

Returns:

The RoundingMode used for this NumberFormat.
getRoundingMode
()

Gets the java.math.RoundingMode used in this NumberFormat.

pack-priv static final NumberFormat
getScientificInstance()

Returns a scientific format for the current default locale.

pack-priv static NumberFormat
getScientificInstance(Locale
the desired locale
inLocale
)

Returns a scientific format for the specified locale.

public int

Returns:

the hash code for this NumberFormat
hashCode
()

Overrides java.lang.Object.hashCode.

Returns the hash code for this NumberFormat.

public boolean

Returns:

true if grouping is used; false otherwise
isGroupingUsed
()

Returns true if grouping is used in this format.

public boolean

Returns:

true if numbers should be parsed as integers only; false otherwise
isParseIntegerOnly
()

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

public boolean

Returns:

true if this format will parse numbers strictly; false otherwise
isStrict
()

Returns true if this format will parse numbers strictly; false otherwise.

pack-priv static String
matchToStyle(NumberFormat fmt, Locale locale)

This method compares the passed NumberFormat to a number of pre-defined style NumberFormat instances, (created with the passed locale).

public abstract Number

Returns:

A Number parsed from the string. In case of failure, returns null.
parse
(String
the String to parse
source
,
ParsePosition
A ParsePosition object with index and error index information as described above.
parsePosition
)

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

public Number

Returns:

A Number parsed from the string.
parse
(String
A String, to be parsed from the beginning.
source
)

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

public final Object

Returns:

A Number parsed from the string. In case of error, returns null.
parseObject
(String
the String to parse
source
,
ParsePosition
A ParsePosition object with index and error index information as described above.
pos
)

Implements abstract java.text.Format.parseObject.

Parses text from the given string to produce an object.

private void
readObject(ObjectInputStream stream)

First, read in the default serializable data.

public void
setCurrency(Currency
the new currency to be used by this number format
currency
)

Sets the currency used by this number format when formatting currency values.

public void
setGroupingUsed(boolean
true if grouping is used; false otherwise
newValue
)

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

public void
setMaximumFractionDigits(int
the maximum number of fraction digits to be shown. 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 during formatting.

public void
setMaximumIntegerDigits(int
the maximum number of integer digits to be shown. 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 integer portion of a number during formatting.

public void
setMinimumFractionDigits(int
the minimum number of fraction digits to be shown. The concrete subclass may 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 during formatting.

public void
setMinimumIntegerDigits(int
the minimum number of integer digits to be shown. The concrete subclass may 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 during formatting.

public void
setParseIntegerOnly(boolean
true if numbers should be parsed as integers only; false otherwise
value
)

Sets whether or not numbers should be parsed as integers only.

public void
setRoundingMode(RoundingMode
The RoundingMode to be used
roundingMode
)

Sets the java.math.RoundingMode used in this NumberFormat.

public void
setStrict(boolean
true if parsing should be done strictly; false otherwise
strict
)

Change the leniency value for parsing.

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 java.text.Format:
createAttributedCharacterIteratorcreateAttributedCharacterIteratorcreateAttributedCharacterIteratorcreateAttributedCharacterIteratorformatformatToCharacterIteratorparseObject