Skip to content

Most visited

Recently visited

navigation
Added in API level 1

NumberFormat

public abstract class NumberFormat
extends Format

java.lang.Object
   ↳ java.text.Format
     ↳ java.text.NumberFormat
Known Direct Subclasses


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 default number format. Use getIntegerInstance() to get an integer number format, getCurrencyInstance() to get the currency number format, and getPercentInstance() 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 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. For example, setParseIntegerOnly only affects parsing: If set to true, "3456.78" is parsed as 3456 (and leaves the parse position just after '6'); if set to false, "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 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 to 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. 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

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

See also:

Summary

Nested classes

class NumberFormat.Field

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

Constants

int FRACTION_FIELD

Field constant identifying the fractional part of a number.

int INTEGER_FIELD

Field constant identifying the integer part of a number.

Protected constructors

NumberFormat()

Used by subclasses.

Public methods

Object clone()

Returns a new NumberFormat with the same properties.

boolean equals(Object object)

Compares the specified object to this number format and indicates if they are equal.

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.

final String format(long value)

Formats the specified long using the rules of this number format.

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.

StringBuffer format(Object object, StringBuffer buffer, FieldPosition field)

Formats a number into a supplied buffer.

final String format(double value)

Formats the specified double using the rules of this number format.

static Locale[] getAvailableLocales()

Returns an array of locales for which custom NumberFormat instances are available.

Currency getCurrency()

Returns the currency used by this number format.

final static NumberFormat getCurrencyInstance()

Returns a NumberFormat for formatting and parsing currency values for the user's default locale.

static NumberFormat getCurrencyInstance(Locale locale)

Returns a NumberFormat for formatting and parsing currency values for the specified locale.

static NumberFormat getInstance(Locale locale)

Returns a NumberFormat for formatting and parsing numbers for the specified locale.

final static NumberFormat getInstance()

Returns a NumberFormat for formatting and parsing numbers for the default locale.

static NumberFormat getIntegerInstance(Locale locale)

Returns a NumberFormat for formatting and parsing integers for the specified locale.

final static NumberFormat getIntegerInstance()

Returns a NumberFormat for formatting and parsing integers for the user's default locale.

int getMaximumFractionDigits()

Returns the maximum number of fraction digits that are printed when formatting.

int getMaximumIntegerDigits()

Returns the maximum number of integer digits that are printed when formatting.

int getMinimumFractionDigits()

Returns the minimum number of fraction digits that are printed when formatting.

int getMinimumIntegerDigits()

Returns the minimum number of integer digits that are printed when formatting.

final static NumberFormat getNumberInstance()

Returns a NumberFormat for formatting and parsing numbers for the user's default locale.

static NumberFormat getNumberInstance(Locale locale)

Returns a NumberFormat for formatting and parsing numbers for the specified locale.

final static NumberFormat getPercentInstance()

Returns a NumberFormat for formatting and parsing percentage values for the user's default locale.

static NumberFormat getPercentInstance(Locale locale)

Returns a NumberFormat for formatting and parsing percentage values for the given locale.

RoundingMode getRoundingMode()

Returns the RoundingMode used by this NumberFormat.

int hashCode()

Returns an integer hash code for this object.

boolean isGroupingUsed()

Indicates whether this number format formats and parses numbers using a grouping separator.

boolean isParseIntegerOnly()

Returns true if this number format only parses integer numbers.

Number parse(String string)

Parses a Number from the specified string using the rules of this number format.

abstract Number parse(String string, ParsePosition position)

Parses a Number from the specified string starting at the index specified by position.

final Object parseObject(String string, ParsePosition position)

Parses the specified string starting at the index specified by position.

void setCurrency(Currency currency)

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

void setGroupingUsed(boolean value)

Sets whether this number format formats and parses numbers using a grouping separator.

void setMaximumFractionDigits(int value)

Sets the maximum number of fraction digits that are printed when formatting.

void setMaximumIntegerDigits(int value)

Sets the new maximum count of integer digits that are printed when formatting.

void setMinimumFractionDigits(int value)

Sets the minimum number of fraction digits that are printed when formatting.

void setMinimumIntegerDigits(int value)

Sets the minimum number of integer digits that are printed when formatting.

void setParseIntegerOnly(boolean value)

Specifies if this number format should parse numbers only as integers or else as any kind of number.

void setRoundingMode(RoundingMode roundingMode)

Sets the RoundingMode used by this NumberFormat.

Inherited methods

From class java.text.Format
From class java.lang.Object

Constants

FRACTION_FIELD

Added in API level 1
int FRACTION_FIELD

Field constant identifying the fractional part of a number.

Constant Value: 1 (0x00000001)

INTEGER_FIELD

Added in API level 1
int INTEGER_FIELD

Field constant identifying the integer part of a number.

Constant Value: 0 (0x00000000)

Protected constructors

NumberFormat

Added in API level 1
NumberFormat ()

Used by subclasses. This was public in Java 5.

Public methods

clone

Added in API level 1
Object clone ()

Returns a new NumberFormat with the same properties.

Returns
Object a shallow copy of this format.

equals

Added in API level 1
boolean equals (Object object)

Compares the specified object to this number format and indicates if they are equal. In order to be equal, object must be an instance of NumberFormat with the same pattern and properties.

Parameters
object Object: the object to compare with this object.
Returns
boolean true if the specified object is equal to this number format; false otherwise.

See also:

format

Added in API level 1
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 field member of position contains a value specifying a format field, then its beginIndex and endIndex members will be updated with the position of the first occurrence of this field in the formatted text.

Parameters
value long: the long to format.
buffer StringBuffer: the target string buffer to append the formatted long value to.
field FieldPosition: on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.
Returns
StringBuffer the string buffer.

format

Added in API level 1
String format (long value)

Formats the specified long using the rules of this number format.

Parameters
value long: the long to format.
Returns
String the formatted string.

format

Added in API level 1
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 field member of position contains a value specifying a format field, then its beginIndex and endIndex members will be updated with the position of the first occurrence of this field in the formatted text.

Parameters
value double: the double to format.
buffer StringBuffer: the target string buffer to append the formatted double value to.
field FieldPosition: on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.
Returns
StringBuffer the string buffer.

format

Added in API level 1
StringBuffer format (Object object, 
                StringBuffer buffer, 
                FieldPosition field)

Formats a number into a supplied buffer.

The number must be a subclass of Number. Instances of Byte, Short, Integer, and Long have Number.longValue invoked, as do instances of BigInteger where BigInteger.bitLength returns less than 64. All other values have Number.doubleValue invoked instead.

If the field member of field contains a value specifying a format field, then its beginIndex and endIndex members will be updated with the position of the first occurrence of this field in the formatted text.

Parameters
object Object: the object to format, must be a Number.
buffer StringBuffer: the target string buffer to append the formatted number to.
field FieldPosition: on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.
Returns
StringBuffer the string buffer.
Throws
IllegalArgumentException if object is not an instance of Number.

format

Added in API level 1
String format (double value)

Formats the specified double using the rules of this number format.

Parameters
value double: the double to format.
Returns
String the formatted string.

getAvailableLocales

Added in API level 1
Locale[] getAvailableLocales ()

Returns an array of locales for which custom NumberFormat instances are available.

Note that Android does not support user-supplied locale service providers.

Returns
Locale[]

getCurrency

Added in API level 1
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
Currency the currency that was set in getInstance() or in setCurrency(), or null.
Throws
UnsupportedOperationException

getCurrencyInstance

Added in API level 1
NumberFormat getCurrencyInstance ()

Returns a NumberFormat for formatting and parsing currency values for the user's default locale. See "Be wary of the default locale".

Returns
NumberFormat a NumberFormat for handling currency values.

getCurrencyInstance

Added in API level 1
NumberFormat getCurrencyInstance (Locale locale)

Returns a NumberFormat for formatting and parsing currency values for the specified locale.

Parameters
locale Locale: the locale to use.
Returns
NumberFormat a NumberFormat for handling currency values.

getInstance

Added in API level 1
NumberFormat getInstance (Locale locale)

Returns a NumberFormat for formatting and parsing numbers for the specified locale.

Parameters
locale Locale: the locale to use.
Returns
NumberFormat a NumberFormat for handling Number objects.

getInstance

Added in API level 1
NumberFormat getInstance ()

Returns a NumberFormat for formatting and parsing numbers for the default locale.

Returns
NumberFormat a NumberFormat for handling Number objects.

getIntegerInstance

Added in API level 1
NumberFormat getIntegerInstance (Locale locale)

Returns a NumberFormat for formatting and parsing integers for the specified locale.

Parameters
locale Locale: the locale to use.
Returns
NumberFormat a NumberFormat for handling integers.

getIntegerInstance

Added in API level 1
NumberFormat getIntegerInstance ()

Returns a NumberFormat for formatting and parsing integers for the user's default locale. See "Be wary of the default locale".

Returns
NumberFormat a NumberFormat for handling integers.

getMaximumFractionDigits

Added in API level 1
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
int the maximum number of fraction digits.

getMaximumIntegerDigits

Added in API level 1
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
int the maximum number of integer digits.

getMinimumFractionDigits

Added in API level 1
int getMinimumFractionDigits ()

Returns the minimum number of fraction digits that are printed when formatting.

Returns
int the minimum number of fraction digits.

getMinimumIntegerDigits

Added in API level 1
int getMinimumIntegerDigits ()

Returns the minimum number of integer digits that are printed when formatting.

Returns
int the minimum number of integer digits.

getNumberInstance

Added in API level 1
NumberFormat getNumberInstance ()

Returns a NumberFormat for formatting and parsing numbers for the user's default locale. See "Be wary of the default locale".

Returns
NumberFormat a NumberFormat for handling Number objects.

getNumberInstance

Added in API level 1
NumberFormat getNumberInstance (Locale locale)

Returns a NumberFormat for formatting and parsing numbers for the specified locale.

Parameters
locale Locale: the locale to use.
Returns
NumberFormat a NumberFormat for handling Number objects.

getPercentInstance

Added in API level 1
NumberFormat getPercentInstance ()

Returns a NumberFormat for formatting and parsing percentage values for the user's default locale. See "Be wary of the default locale".

The NumberFormat returned 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).

Returns
NumberFormat

getPercentInstance

Added in API level 1
NumberFormat getPercentInstance (Locale locale)

Returns a NumberFormat for formatting and parsing percentage values for the given locale.

The NumberFormat returned 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).

Parameters
locale Locale
Returns
NumberFormat

getRoundingMode

Added in API level 9
RoundingMode getRoundingMode ()

Returns the RoundingMode used by this NumberFormat. The default implementation in NumberFormat throws UnsupportedOperationException. Subclasses for which a rounding mode is meaningful are expected to override this method.

Returns
RoundingMode

hashCode

Added in API level 1
int hashCode ()

Returns an integer hash code for this object. By contract, any two objects for which equals(Object) returns true must return the same hash code value. This means that subclasses of Object usually 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 hashCode method if you intend implementing your own hashCode method.

Returns
int this object's hash code.

isGroupingUsed

Added in API level 1
boolean isGroupingUsed ()

Indicates whether this number format formats and parses numbers using a grouping separator.

Returns
boolean true if a grouping separator is used; false otherwise.

isParseIntegerOnly

Added in API level 1
boolean isParseIntegerOnly ()

Returns true if this number format only parses integer numbers. Parsing stops if a decimal separator is encountered.

Returns
boolean

parse

Added in API level 1
Number parse (String string)

Parses a Number from the specified string using the rules of this number format.

Parameters
string String: the string to parse.
Returns
Number the Number resulting from the parsing.
Throws
ParseException if an error occurs during parsing.

parse

Added in API level 1
Number parse (String string, 
                ParsePosition position)

Parses a Number from the specified string starting at the index specified by position. If the string is successfully parsed then the index of the ParsePosition is updated to the index following the parsed text. On error, the index is unchanged and the error index of ParsePosition is set to the index where the error occurred.

Parameters
string String: the string to parse.
position ParsePosition: input/output parameter, specifies the start index in string from 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
Number the Number resulting from the parse or null if there is an error.

parseObject

Added in API level 1
Object parseObject (String string, 
                ParsePosition position)

Parses the specified string starting at the index specified by position. If the string is successfully parsed then the index of the ParsePosition is updated to the index following the parsed text. On error, the index is unchanged and the error index of ParsePosition is set to the index where the error occurred.

Parameters
string String: the string to parse.
position ParsePosition: input/output parameter, specifies the start index in string from 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
Object the object resulting from the parse or null if there is an error.

setCurrency

Added in API level 1
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 Currency: the new currency.
Throws
UnsupportedOperationException

setGroupingUsed

Added in API level 1
void setGroupingUsed (boolean value)

Sets whether this number format formats and parses numbers using a grouping separator.

Parameters
value boolean: true if a grouping separator is used; false otherwise.

setMaximumFractionDigits

Added in API level 1
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 int: the maximum number of fraction digits.

setMaximumIntegerDigits

Added in API level 1
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 int: the new maximum number of integer numerals for display.

setMinimumFractionDigits

Added in API level 1
void setMinimumFractionDigits (int value)

Sets the minimum number of fraction digits that are printed when formatting.

Parameters
value int: the minimum number of fraction digits.

setMinimumIntegerDigits

Added in API level 1
void setMinimumIntegerDigits (int value)

Sets the minimum number of integer digits that are printed when formatting.

Parameters
value int: the minimum number of integer digits.

setParseIntegerOnly

Added in API level 1
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 a true value then subsequent parsing attempts will stop if a decimal separator is encountered.

Parameters
value boolean: true to only parse integers, false to parse integers as well as fractions.

setRoundingMode

Added in API level 9
void setRoundingMode (RoundingMode roundingMode)

Sets the RoundingMode used by this NumberFormat. The default implementation in NumberFormat throws UnsupportedOperationException. Subclasses for which a rounding mode is meaningful are expected to override this method.

Parameters
roundingMode RoundingMode
This site uses cookies to store your preferences for site-specific language and display options.

Hooray!

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.