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.
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.
getInstance() or getNumberInstance() to get
a decimal format. For example, "2,000.5".
getIntegerInstance() to get an integer number format.
For example, "2,000".
getCurrencyInstance to get a currency number format.
For example, "$2,000.50".
getCompactNumberInstance to get a compact number format.
For example, "2K".
getPercentInstance to get a format for displaying percentages.
For example, "200,050%".
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.
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.
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US); currencyFormat.format(100000); // returns "$100,000.00" currencyFormat.parse("$100,000.00"); // returns 100000
NumberFormat provides API to customize formatting and parsing behavior,
setParseIntegerOnly(boolean); when true, will only return the
integer portion of the number parsed from the String.
setMinimumFractionDigits(int); Use to adjust the expected digits
when formatting. Use any of the other minimum/maximum or fraction/integer
setter methods in the same manner. These methods have no impact on parsing behavior.
setGroupingUsed(boolean); when true, formatted numbers will be displayed
with grouping separators. Additionally, when false, parsing will not expect
grouping separators in the parsed String.
setStrict(boolean); when true, parsing will be done strictly.
The behavior of strict parsing should be referred to in the implementing
NumberFormat subclass.
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 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:
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.
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.
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.
Implementation Specification
Null Parameter Handling
format(double, StringBuffer, FieldPosition),
format(long, StringBuffer, FieldPosition) and
parse(String, ParsePosition) methods may throw
NullPointerException, if any of their parameter is null.
The subclass may provide its own implementation and specification about
NullPointerException.
java.math.RoundingMode for formatting numbers. It
uses the round half-even algorithm. To change the rounding mode use
setRoundingMode.
The NumberFormat returned by the static factory methods is
configured to round floating point numbers using half-even
rounding (see RoundingMode.HALF_EVEN ) for formatting.
DecimalFormat, ChoiceFormat, CompactNumberFormat, Locale
| Modifier and Type | Class and Description |
|---|---|
| public static class | NumberFormat.
Defines constants that are used as attribute keys in the
|
| public static enum | NumberFormat.
A number format style. |
| Modifier and Type | Field 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 |
| pack-priv static final long |
| Access | Constructor and Description |
|---|---|
| protected |
| Modifier and Type | Method and Description |
|---|---|
| public Object | |
| public boolean | Returns: true if the specified object is equal to this NumberFormatobject to be compared for equality obj)Overrides java. Compares the specified object with this |
| pack-priv String | |
| public StringBuffer | Returns: the value passed in astoAppendTothe number to format number, StringBuffer the toAppendTo, FieldPosition StringBuffer to which the formatted
text is to be appendedkeeps track on the position of the field within the
returned string. For example, for formatting a number
pos)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.Implements abstract java. Formats a number and appends the resulting text to the given string buffer. |
| pack-priv Format. | format(Object number, Format.
Overrides java.
|
| public final String | Returns: the formatted Stringthe double number to format number)Specialization of format. |
| public final String | |
| public abstract StringBuffer | Returns: the formatted StringBufferthe 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
pos)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.Specialization of format. |
| pack-priv Format. | |
| public abstract StringBuffer | Returns: the formatted StringBufferthe 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
pos)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.Specialization of format. |
| pack-priv Format. | |
| public static Locale[] | Returns: An array of locales for which localizedNumberFormat instances are available.Returns an array of all locales for which the
|
| public static NumberFormat | Returns: ANumberFormat instance for compact number
formattingReturns a compact number format for the default
|
| public static NumberFormat | Returns: ANumberFormat instance for compact number
formattingthe desired locale locale, NumberFormat.the style for formatting a number formatStyleReturns a compact number format for the specified |
| public Currency | Returns: the currency used by this number format, ornullGets the currency used by this number format when formatting currency values. |
| public static final NumberFormat | Returns: theNumberFormat instance for currency formattingReturns a currency format for the current default
|
| public static NumberFormat | Returns: theNumberFormat instance for currency formattingthe desired locale inLocale)Returns a currency format for the specified locale. |
| public static final NumberFormat | Returns: theNumberFormat instance for general-purpose number
formattingReturns a general-purpose number format for the current default
|
| public static NumberFormat | Returns: theNumberFormat instance for general-purpose number
formattingthe desired locale inLocale)Returns a general-purpose number format for the specified locale. |
| private static NumberFormat | |
| private static NumberFormat | getInstance(LocaleProviderAdapter adapter, Locale locale, NumberFormat.
|
| public static final NumberFormat | Returns: a number format for integer valuesReturns an integer number format for the current default
|
| public static NumberFormat | Returns: a number format for integer valuesthe desired locale inLocale)Returns an integer number format for the specified locale. |
| public int | Returns: the maximum number of digits.Returns the maximum number of digits allowed in the fraction portion of a number during formatting. |
| public int | Returns: the maximum number of digitsReturns the maximum number of digits allowed in the integer portion of a number during formatting. |
| public int | Returns: the minimum number of digitsReturns the minimum number of digits allowed in the fraction portion of a number during formatting. |
| public int | Returns: the minimum number of digitsReturns the minimum number of digits allowed in the integer portion of a number during formatting. |
| public static final NumberFormat | Returns: theNumberFormat instance for general-purpose number
formattingReturns a general-purpose number format for the current default
|
| public static NumberFormat | Returns: theNumberFormat instance for general-purpose number
formattingthe desired locale inLocale)Returns a general-purpose number format for the specified locale. |
| public static final NumberFormat | Returns: theNumberFormat instance for percentage formattingReturns a percentage format for the current default
|
| public static NumberFormat | Returns: theNumberFormat instance for percentage formattingthe desired locale inLocale)Returns a percentage format for the specified locale. |
| public RoundingMode | Returns: TheRoundingMode used for this NumberFormat.Gets the |
| pack-priv static final NumberFormat | |
| 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 thisNumberFormatOverrides java. Returns the hash code for this |
| public boolean | Returns: true if grouping is used;
false otherwiseReturns true if grouping is used in this format. |
| public boolean | Returns: true if numbers should be parsed as integers only;
false otherwiseReturns |
| public boolean | Returns: true if this format will parse numbers strictly;
false otherwiseReturns |
| 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: ANumber parsed from the string. In case of
failure, returns null.the source, ParsePosition String to parseA parsePosition)ParsePosition object with index and error
index information as described above.Parses text from the beginning of the given string to produce a |
| public Number | |
| public final Object | Returns: ANumber parsed from the string. In case of
error, returns null.the source, ParsePosition String to parseA pos)ParsePosition object with index and error
index information as described above.Implements abstract java. Parses text from the given string to produce an object. |
| private void | |
| 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 otherwiseSet 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 otherwiseSets whether or not numbers should be parsed as integers only. |
| public void | setRoundingMode(RoundingMode
The roundingMode)RoundingMode to be usedSets the |
| public void | setStrict(boolean
true if parsing should be done strictly;
false otherwiseChange the leniency value for parsing. |
| private void | writeObject(ObjectOutputStream stream)
Write out the default serializable data, after first setting
the |