Class NumberFormat
- java.lang.Object
-
- java.text.Format
-
- java.text.NumberFormat
-
- All Implemented Interfaces:
Serializable,Cloneable
- Direct Known Subclasses:
ChoiceFormat,DecimalFormat
public abstract class NumberFormat extends Format
The abstract base class for all number formats. This class provides the interface for formatting and parsing numbers.NumberFormatalso provides methods for determining which locales have number formats, and what their names are.NumberFormathelps 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
NumberFormatto parse numbers:myNumber = nf.parse(myString);
Use
#getInstanceor#getNumberInstanceto get the default number format. UsegetIntegerInstance()to get an integer number format,getCurrencyInstance()to get the currency number format, andgetPercentInstance()to get a format for displaying percentages.You can also control the display of numbers with methods such 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 theNumberFormatyou get from the factory methods to aDecimalFormat. This will work for the vast majority of locales; just remember to put it in atryblock in case you encounter an unusual one.NumberFormatis designed such that some controls work for formatting and others work for parsing. For example,setParseIntegerOnlyonly affects parsing: If set totrue, "3456.78" is parsed as 3456 (and leaves the parse position just after '6'); if set tofalse, "3456.78" is parsed as 3456.78 (and leaves the parse position just after '8'). This is independent of formatting.You can also use forms of the
parseandformatmethods withParsePositionandFieldPositionto allow you to:- progressively parse through pieces of a string;
- align the decimal point and other areas.
- If you are using a monospaced font with spacing for alignment, you can
pass the
FieldPositionin your format call, withfield=INTEGER_FIELD. On output,getEndIndexwill be set to the offset between the last character of the integer and the decimal. Add (desiredSpaceCount - getEndIndex) spaces to the front of the string. - 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. This also works where there is no decimal but possibly additional characters before or after the number, for example 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
DecimalFormatis the concrete implementation ofNumberFormat, and theNumberFormatAPI is essentially an abstraction ofDecimalFormat'sAPI. Refer toDecimalFormatfor more information about this API.- See Also:
DecimalFormat,ChoiceFormat, Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classNumberFormat.FieldThe instances of this inner class are used as attribute keys and values inAttributedCharacterIteratorthat theFormat.formatToCharacterIterator(Object)method returns.
-
Field Summary
Fields Modifier and Type Field Description static intFRACTION_FIELDField constant identifying the fractional part of a number.static intINTEGER_FIELDField constant identifying the integer part of a number.
-
Constructor Summary
Constructors Modifier Constructor Description protectedNumberFormat()Used by subclasses.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description Objectclone()Returns a newNumberFormatwith the same properties.booleanequals(Object object)Compares the specified object to this number format and indicates if they are equal.Stringformat(double value)Formats the specified double using the rules of this number format.abstract StringBufferformat(double value, StringBuffer buffer, FieldPosition field)Formats the specified double value as a string using the pattern of this number format and appends the string to the specified string buffer.Stringformat(long value)Formats the specified long using the rules of this number format.abstract StringBufferformat(long value, StringBuffer buffer, FieldPosition field)Formats the specified long value as a string using the pattern of this number format and appends the string to the specified string buffer.StringBufferformat(Object object, StringBuffer buffer, FieldPosition field)Formats a number into a supplied buffer.static Locale[]getAvailableLocales()Returns an array of locales for which customNumberFormatinstances are available.CurrencygetCurrency()Returns the currency used by this number format.static NumberFormatgetCurrencyInstance()Returns aNumberFormatfor formatting and parsing currency values for the user's default locale.static NumberFormatgetCurrencyInstance(Locale locale)Returns aNumberFormatfor formatting and parsing currency values for the specified locale.static NumberFormatgetInstance()Returns aNumberFormatfor formatting and parsing numbers for the default locale.static NumberFormatgetInstance(Locale locale)Returns aNumberFormatfor formatting and parsing numbers for the specified locale.static NumberFormatgetIntegerInstance()Returns aNumberFormatfor formatting and parsing integers for the user's default locale.static NumberFormatgetIntegerInstance(Locale locale)Returns aNumberFormatfor formatting and parsing integers for the specified locale.intgetMaximumFractionDigits()Returns the maximum number of fraction digits that are printed when formatting.intgetMaximumIntegerDigits()Returns the maximum number of integer digits that are printed when formatting.intgetMinimumFractionDigits()Returns the minimum number of fraction digits that are printed when formatting.intgetMinimumIntegerDigits()Returns the minimum number of integer digits that are printed when formatting.static NumberFormatgetNumberInstance()Returns aNumberFormatfor formatting and parsing numbers for the user's default locale.static NumberFormatgetNumberInstance(Locale locale)Returns aNumberFormatfor formatting and parsing numbers for the specified locale.static NumberFormatgetPercentInstance()Returns aNumberFormatfor formatting and parsing percentage values for the user's default locale.static NumberFormatgetPercentInstance(Locale locale)Returns aNumberFormatfor formatting and parsing percentage values for the givenlocale.RoundingModegetRoundingMode()Returns theRoundingModeused by thisNumberFormat.inthashCode()Returns an integer hash code for this object.booleanisGroupingUsed()Indicates whether this number format formats and parses numbers using a grouping separator.booleanisParseIntegerOnly()Returns true if this number format only parses integer numbers.Numberparse(String string)Parses aNumberfrom the specified string using the rules of this number format.abstract Numberparse(String string, ParsePosition position)Parses aNumberfrom the specified string starting at the index specified byposition.ObjectparseObject(String string, ParsePosition position)Parses the specified string starting at the index specified byposition.voidsetCurrency(Currency currency)Sets the currency used by this number format when formatting currency values.voidsetGroupingUsed(boolean value)Sets whether this number format formats and parses numbers using a grouping separator.voidsetMaximumFractionDigits(int value)Sets the maximum number of fraction digits that are printed when formatting.voidsetMaximumIntegerDigits(int value)Sets the new maximum count of integer digits that are printed when formatting.voidsetMinimumFractionDigits(int value)Sets the minimum number of fraction digits that are printed when formatting.voidsetMinimumIntegerDigits(int value)Sets the minimum number of integer digits that are printed when formatting.voidsetParseIntegerOnly(boolean value)Specifies if this number format should parse numbers only as integers or else as any kind of number.voidsetRoundingMode(RoundingMode roundingMode)Sets theRoundingModeused by thisNumberFormat.-
Methods inherited from class java.text.Format
format, formatToCharacterIterator, parseObject
-
-
-
-
Field Detail
-
INTEGER_FIELD
public static final int INTEGER_FIELD
Field constant identifying the integer part of a number.- See Also:
- Constant Field Values
-
FRACTION_FIELD
public static final int FRACTION_FIELD
Field constant identifying the fractional part of a number.- See Also:
- Constant Field Values
-
-
Method Detail
-
clone
public Object clone()
Returns a newNumberFormatwith the same properties.
-
equals
public boolean equals(Object object)
Compares the specified object to this number format and indicates if they are equal. In order to be equal,objectmust be an instance ofNumberFormatwith the same pattern and properties.- Overrides:
equalsin classObject- Parameters:
object- the object to compare with this object.- Returns:
trueif the specified object is equal to this number format;falseotherwise.- See Also:
hashCode()
-
format
public final String format(double value)
Formats the specified double using the rules of this number format.- Parameters:
value- the double to format.- Returns:
- the formatted string.
-
format
public abstract StringBuffer format(double value, StringBuffer buffer, FieldPosition field)
Formats the specified double value as a string using the pattern of this number format and appends the string to the specified string buffer.If the
fieldmember ofpositioncontains a value specifying a format field, then itsbeginIndexandendIndexmembers will be updated with the position of the first occurrence of this field in the formatted text.- Parameters:
value- the double to format.buffer- the target string buffer to append the formatted double value to.field- on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.- Returns:
- the string buffer.
-
format
public final String format(long value)
Formats the specified long using the rules of this number format.- Parameters:
value- the long to format.- Returns:
- the formatted string.
-
format
public abstract StringBuffer format(long value, StringBuffer buffer, FieldPosition field)
Formats the specified long value as a string using the pattern of this number format and appends the string to the specified string buffer.If the
fieldmember ofpositioncontains a value specifying a format field, then itsbeginIndexandendIndexmembers will be updated with the position of the first occurrence of this field in the formatted text.- Parameters:
value- the long to format.buffer- the target string buffer to append the formatted long value to.field- on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.- Returns:
- the string buffer.
-
format
public StringBuffer format(Object object, StringBuffer buffer, FieldPosition field)
Formats a number into a supplied buffer.The number must be a subclass of
Number. Instances ofByte,Short,Integer, andLonghaveNumber.longValueinvoked, as do instances ofBigIntegerwhereBigInteger.bitLengthreturns less than 64. All other values haveNumber.doubleValueinvoked instead.If the
fieldmember offieldcontains a value specifying a format field, then itsbeginIndexandendIndexmembers will be updated with the position of the first occurrence of this field in the formatted text.- Specified by:
formatin classFormat- Parameters:
object- the object to format, must be aNumber.buffer- the target string buffer to append the formatted number to.field- on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.- Returns:
- the string buffer.
- Throws:
IllegalArgumentException- ifobjectis not an instance ofNumber.
-
getAvailableLocales
public static Locale[] getAvailableLocales()
Returns an array of locales for which customNumberFormatinstances are available.Note that Android does not support user-supplied locale service providers.
-
getCurrency
public Currency getCurrency()
Returns the currency used by this number format.This implementation throws
UnsupportedOperationException, concrete subclasses should override this method if they support currency formatting.- Returns:
- the currency that was set in getInstance() or in setCurrency(),
or
null. - Throws:
UnsupportedOperationException
-
getCurrencyInstance
public static final NumberFormat getCurrencyInstance()
Returns aNumberFormatfor formatting and parsing currency values for the user's default locale. See "Be wary of the default locale".- Returns:
- a
NumberFormatfor handling currency values.
-
getCurrencyInstance
public static NumberFormat getCurrencyInstance(Locale locale)
Returns aNumberFormatfor formatting and parsing currency values for the specified locale.- Parameters:
locale- the locale to use.- Returns:
- a
NumberFormatfor handling currency values.
-
getIntegerInstance
public static final NumberFormat getIntegerInstance()
Returns aNumberFormatfor formatting and parsing integers for the user's default locale. See "Be wary of the default locale".- Returns:
- a
NumberFormatfor handling integers.
-
getIntegerInstance
public static NumberFormat getIntegerInstance(Locale locale)
Returns aNumberFormatfor formatting and parsing integers for the specified locale.- Parameters:
locale- the locale to use.- Returns:
- a
NumberFormatfor handling integers.
-
getInstance
public static final NumberFormat getInstance()
Returns aNumberFormatfor formatting and parsing numbers for the default locale.- Returns:
- a
NumberFormatfor handlingNumberobjects.
-
getInstance
public static NumberFormat getInstance(Locale locale)
Returns aNumberFormatfor formatting and parsing numbers for the specified locale.- Parameters:
locale- the locale to use.- Returns:
- a
NumberFormatfor handlingNumberobjects.
-
getMaximumFractionDigits
public int getMaximumFractionDigits()
Returns the maximum number of fraction digits that are printed when formatting. If the maximum is less than the number of fraction digits, the least significant digits are truncated.- Returns:
- the maximum number of fraction digits.
-
getMaximumIntegerDigits
public int getMaximumIntegerDigits()
Returns the maximum number of integer digits that are printed when formatting. If the maximum is less than the number of integer digits, the most significant digits are truncated.- Returns:
- the maximum number of integer digits.
-
getMinimumFractionDigits
public int getMinimumFractionDigits()
Returns the minimum number of fraction digits that are printed when formatting.- Returns:
- the minimum number of fraction digits.
-
getMinimumIntegerDigits
public int getMinimumIntegerDigits()
Returns the minimum number of integer digits that are printed when formatting.- Returns:
- the minimum number of integer digits.
-
getNumberInstance
public static final NumberFormat getNumberInstance()
Returns aNumberFormatfor formatting and parsing numbers for the user's default locale. See "Be wary of the default locale".- Returns:
- a
NumberFormatfor handlingNumberobjects.
-
getNumberInstance
public static NumberFormat getNumberInstance(Locale locale)
Returns aNumberFormatfor formatting and parsing numbers for the specified locale.- Parameters:
locale- the locale to use.- Returns:
- a
NumberFormatfor handlingNumberobjects.
-
getPercentInstance
public static final NumberFormat getPercentInstance()
Returns aNumberFormatfor formatting and parsing percentage values for the user's default locale. See "Be wary of the default locale".The
NumberFormatreturned by this method should only be used to format floating-point numbers typically between 0 and 1 (with 1 being 100%). A value such as 0.53 will be treated as 53%, but 53.0 (or the integer 53) will be treated as 5,300%, which is rarely what you intended.Non-integer percentages will be rounded according to the rounding mode, so by default 0.142 will be 14% but 0.148 will be 15%. If you want fractional percentages, use
setMaximumFractionDigits(int).
-
getPercentInstance
public static NumberFormat getPercentInstance(Locale locale)
Returns aNumberFormatfor formatting and parsing percentage values for the givenlocale.The
NumberFormatreturned by this method should only be used to format floating-point numbers typically between 0 and 1 (with 1 being 100%). A value such as 0.53 will be treated as 53%, but 53.0 (or the integer 53) will be treated as 5,300%, which is rarely what you intended.Non-integer percentages will be rounded according to the rounding mode, so by default 0.142 will be 14% but 0.148 will be 15%. If you want fractional percentages, use
setMaximumFractionDigits(int).
-
hashCode
public int hashCode()
Description copied from class:ObjectReturns an integer hash code for this object. By contract, any two objects for whichObject.equals(java.lang.Object)returnstruemust return the same hash code value. This means that subclasses ofObjectusually override both methods or neither method.Note that hash values must not change over time unless information used in equals comparisons also changes.
See Writing a correct
hashCodemethod if you intend implementing your ownhashCodemethod.- Overrides:
hashCodein classObject- Returns:
- this object's hash code.
- See Also:
Object.equals(java.lang.Object)
-
isGroupingUsed
public boolean isGroupingUsed()
Indicates whether this number format formats and parses numbers using a grouping separator.- Returns:
trueif a grouping separator is used;falseotherwise.
-
isParseIntegerOnly
public boolean isParseIntegerOnly()
Returns true if this number format only parses integer numbers. Parsing stops if a decimal separator is encountered.
-
parse
public Number parse(String string) throws ParseException
Parses aNumberfrom the specified string using the rules of this number format.- Parameters:
string- the string to parse.- Returns:
- the
Numberresulting from the parsing. - Throws:
ParseException- if an error occurs during parsing.
-
parse
public abstract Number parse(String string, ParsePosition position)
Parses aNumberfrom the specified string starting at the index specified byposition. If the string is successfully parsed then the index of theParsePositionis updated to the index following the parsed text. On error, the index is unchanged and the error index ofParsePositionis set to the index where the error occurred.- Parameters:
string- the string to parse.position- input/output parameter, specifies the start index instringfrom where to start parsing. If parsing is successful, it is updated with the index following the parsed text; on error, the index is unchanged and the error index is set to the index where the error occurred.- Returns:
- the
Numberresulting from the parse ornullif there is an error.
-
parseObject
public final Object parseObject(String string, ParsePosition position)
Description copied from class:FormatParses the specified string starting at the index specified byposition. If the string is successfully parsed then the index of theParsePositionis updated to the index following the parsed text. On error, the index is unchanged and the error index ofParsePositionis set to the index where the error occurred.- Specified by:
parseObjectin classFormat- Parameters:
string- the string to parse.position- input/output parameter, specifies the start index instringfrom where to start parsing. If parsing is successful, it is updated with the index following the parsed text; on error, the index is unchanged and the error index is set to the index where the error occurred.- Returns:
- the object resulting from the parse or
nullif there is an error.
-
setCurrency
public void setCurrency(Currency currency)
Sets the currency used by this number format when formatting currency values. The min and max fraction digits remain the same.This implementation throws
UnsupportedOperationException, concrete subclasses should override this method if they support currency formatting.- Parameters:
currency- the new currency.- Throws:
UnsupportedOperationException
-
setGroupingUsed
public void setGroupingUsed(boolean value)
Sets whether this number format formats and parses numbers using a grouping separator.- Parameters:
value-trueif a grouping separator is used;falseotherwise.
-
setMaximumFractionDigits
public void setMaximumFractionDigits(int value)
Sets the maximum number of fraction digits that are printed when formatting. If the maximum is less than the number of fraction digits, the least significant digits are truncated.- Parameters:
value- the maximum number of fraction digits.
-
setMaximumIntegerDigits
public void setMaximumIntegerDigits(int value)
Sets the new maximum count of integer digits that are printed when formatting. If the maximum is less than the number of integer digits, the most significant digits are truncated.- Parameters:
value- the new maximum number of integer numerals for display.
-
setMinimumFractionDigits
public void setMinimumFractionDigits(int value)
Sets the minimum number of fraction digits that are printed when formatting.- Parameters:
value- the minimum number of fraction digits.
-
setMinimumIntegerDigits
public void setMinimumIntegerDigits(int value)
Sets the minimum number of integer digits that are printed when formatting.- Parameters:
value- the minimum number of integer digits.
-
setParseIntegerOnly
public void setParseIntegerOnly(boolean value)
Specifies if this number format should parse numbers only as integers or else as any kind of number. If this method is called with atruevalue then subsequent parsing attempts will stop if a decimal separator is encountered.- Parameters:
value-trueto only parse integers,falseto parse integers as well as fractions.
-
getRoundingMode
public RoundingMode getRoundingMode()
Returns theRoundingModeused by thisNumberFormat. The default implementation inNumberFormatthrowsUnsupportedOperationException. Subclasses for which a rounding mode is meaningful are expected to override this method.- Since:
- 1.6
-
setRoundingMode
public void setRoundingMode(RoundingMode roundingMode)
Sets theRoundingModeused by thisNumberFormat. The default implementation inNumberFormatthrowsUnsupportedOperationException. Subclasses for which a rounding mode is meaningful are expected to override this method.- Since:
- 1.6
-
-