FileDocCategorySizeDatePackage
NumberFormat.javaAPI DocAndroid 1.5 API35281Wed May 06 22:41:06 BST 2009java.text

NumberFormat

public abstract class NumberFormat extends Format
The abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. {@code NumberFormat} also provides methods for determining which locales have number formats, and what their names are.

{@code 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 {@code getInstance}.

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);

You can also use a {@code NumberFormat} to parse numbers:

myNumber = nf.parse(myString);

Use {@code getInstance} or {@code getNumberInstance} to get the normal number format. Use {@code getIntegerInstance} to get an integer number format. Use {@code getCurrencyInstance} to get the currency number format and use {@code getPercentInstance} to get a format for displaying percentages. With this format, a fraction like 0.53 is displayed as 53%.

You can also control the display of numbers with methods such as {@code 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 {@code NumberFormat} you get from the factory methods to a {@code DecimalFormat}. This will work for the vast majority of locales; just remember to put it in a {@code try} block in case you encounter an unusual one.

{@code NumberFormat} is designed such that some controls work for formatting and others work for parsing. For example, {@code setParseIntegerOnly} only affects parsing: If set to {@code true}, "3456.78" is parsed as 3456 (and leaves the parse position just after '6'); if set to {@code 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 {@code parse} and {@code format} methods with {@code ParsePosition} and {@code FieldPosition} to allow you to:

  • progressively parse through pieces of a string;
  • align the decimal point and other areas.
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 {@code FieldPosition} in your format call, with {@code field} = {@code INTEGER_FIELD}. On output, {@code 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 {@code 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

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

see
DecimalFormat
see
java.text.ChoiceFormat
since
Android 1.0

Fields Summary
private static final long
serialVersionUID
public static final int
INTEGER_FIELD
Field constant identifying the integer part of a number.
public static final int
FRACTION_FIELD
Field constant identifying the fractional part of a number.
private boolean
groupingUsed
private boolean
parseIntegerOnly
private int
maximumIntegerDigits
private int
minimumIntegerDigits
private int
maximumFractionDigits
private int
minimumFractionDigits
private static final ObjectStreamField[]
serialPersistentFields
Constructors Summary
public NumberFormat()
Constructs a new instance of {@code NumberFormat}.

since
Android 1.0


                    
      
    
Methods Summary
public java.lang.Objectclone()
Returns a new {@code NumberFormat} with the same properties as this {@code NumberFormat}.

return
a shallow copy of this {@code NumberFormat}.
see
java.lang.Cloneable
since
Android 1.0

        return super.clone();
    
public booleanequals(java.lang.Object object)
Compares the specified object to this number format and indicates if they are equal. In order to be equal, {@code object} must be an instance of {@code NumberFormat} with the same pattern and properties.

param
object the object to compare with this object.
return
{@code true} if the specified object is equal to this number format; {@code false} otherwise.
see
#hashCode
since
Android 1.0

        if (object == this) {
            return true;
        }
        if (!(object instanceof NumberFormat)) {
            return false;
        }
        NumberFormat obj = (NumberFormat) object;
        return groupingUsed == obj.groupingUsed
                && parseIntegerOnly == obj.parseIntegerOnly
                && maximumFractionDigits == obj.maximumFractionDigits
                && maximumIntegerDigits == obj.maximumIntegerDigits
                && minimumFractionDigits == obj.minimumFractionDigits
                && minimumIntegerDigits == obj.minimumIntegerDigits;
    
public final java.lang.Stringformat(double value)
Formats the specified double using the rules of this number format.

param
value the double to format.
return
the formatted string.
since
Android 1.0

        return format(value, new StringBuffer(), new FieldPosition(0))
                .toString();
    
public abstract java.lang.StringBufferformat(double value, java.lang.StringBuffer buffer, java.text.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 {@code field} member of {@code position} contains a value specifying a format field, then its {@code beginIndex} and {@code endIndex} members will be updated with the position of the first occurrence of this field in the formatted text.

param
value the double to format.
param
buffer the target string buffer to append the formatted double value to.
param
field on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.
return
the string buffer.
since
Android 1.0

public final java.lang.Stringformat(long value)
Formats the specified long using the rules of this number format.

param
value the long to format.
return
the formatted string.
since
Android 1.0

        return format(value, new StringBuffer(), new FieldPosition(0))
                .toString();
    
public abstract java.lang.StringBufferformat(long value, java.lang.StringBuffer buffer, java.text.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 {@code field} member of {@code position} contains a value specifying a format field, then its {@code beginIndex} and {@code endIndex} members will be updated with the position of the first occurrence of this field in the formatted text.

param
value the long to format.
param
buffer the target string buffer to append the formatted long value to.
param
field on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.
return
the string buffer.
since
Android 1.0

public java.lang.StringBufferformat(java.lang.Object object, java.lang.StringBuffer buffer, java.text.FieldPosition field)
Formats the specified object as a string using the pattern of this number format and appends the string to the specified string buffer.

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

param
object the object to format, must be a {@code Number}.
param
buffer the target string buffer to append the formatted number to.
param
field on input: an optional alignment field; on output: the offsets of the alignment field in the formatted text.
return
the string buffer.
throws
IllegalArgumentException if {@code object} is not an instance of {@code Number}.
since
Android 1.0

        if (object instanceof Number) {
            double dv = ((Number) object).doubleValue();
            long lv = ((Number) object).longValue();
            if (dv == lv) {
                return format(lv, buffer, field);
            }
            return format(dv, buffer, field);
        }
        throw new IllegalArgumentException();
    
public static java.util.Locale[]getAvailableLocales()
Gets the list of installed locales which support {@code NumberFormat}.

return
an array of locales.
since
Android 1.0

        return Locale.getAvailableLocales();
    
public java.util.CurrencygetCurrency()
Returns the currency used by this number format.

This implementation throws {@code UnsupportedOperationException}, concrete subclasses should override this method if they support currency formatting.

return
the currency that was set in getInstance() or in setCurrency(), or {@code null}.
throws
UnsupportedOperationException
since
Android 1.0

        throw new UnsupportedOperationException();
    
public static final java.text.NumberFormatgetCurrencyInstance()
Returns a {@code NumberFormat} for formatting and parsing currency values for the default locale.

return
a {@code NumberFormat} for handling currency values.
since
Android 1.0

        return getCurrencyInstance(Locale.getDefault());
    
public static java.text.NumberFormatgetCurrencyInstance(java.util.Locale locale)
Returns a {@code NumberFormat} for formatting and parsing currency values for the specified locale.

param
locale the locale to use.
return
a {@code NumberFormat} for handling currency values.
since
Android 1.0

        return getInstance(locale, "Currency"); //$NON-NLS-1$
    
public static final java.text.NumberFormatgetInstance()
Returns a {@code NumberFormat} for formatting and parsing numbers for the default locale.

return
a {@code NumberFormat} for handling {@code Number} objects.
since
Android 1.0

        return getNumberInstance();
    
public static java.text.NumberFormatgetInstance(java.util.Locale locale)
Returns a {@code NumberFormat} for formatting and parsing numbers for the specified locale.

param
locale the locale to use.
return
a {@code NumberFormat} for handling {@code Number} objects.
since
Android 1.0

        return getNumberInstance(locale);
    
static java.text.NumberFormatgetInstance(java.util.Locale locale, java.lang.String type)

        return new DecimalFormat(getPattern(locale, type),
                new DecimalFormatSymbols(locale));
    
public static final java.text.NumberFormatgetIntegerInstance()
Returns a {@code NumberFormat} for formatting and parsing integers for the default locale.

return
a {@code NumberFormat} for handling integers.
since
Android 1.0

        return getIntegerInstance(Locale.getDefault());
    
public static java.text.NumberFormatgetIntegerInstance(java.util.Locale locale)
Returns a {@code NumberFormat} for formatting and parsing integers for the specified locale.

param
locale the locale to use.
return
a {@code NumberFormat} for handling integers.
since
Android 1.0

        NumberFormat format = getInstance(locale, "Integer"); //$NON-NLS-1$
        format.setParseIntegerOnly(true);
        return format;
    
public intgetMaximumFractionDigits()
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.

return
the maximum number of fraction digits.
since
Android 1.0

        return maximumFractionDigits;
    
public intgetMaximumIntegerDigits()
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.

return
the maximum number of integer digits.
since
Android 1.0

        return maximumIntegerDigits;
    
public intgetMinimumFractionDigits()
Returns the minimum number of fraction digits that are printed when formatting.

return
the minimum number of fraction digits.
since
Android 1.0

        return minimumFractionDigits;
    
public intgetMinimumIntegerDigits()
Returns the minimum number of integer digits that are printed when formatting.

return
the minimum number of integer digits.
since
Android 1.0

        return minimumIntegerDigits;
    
public static final java.text.NumberFormatgetNumberInstance()
Returns a {@code NumberFormat} for formatting and parsing numbers for the default locale.

return
a {@code NumberFormat} for handling {@code Number} objects.
since
Android 1.0

        return getNumberInstance(Locale.getDefault());
    
public static java.text.NumberFormatgetNumberInstance(java.util.Locale locale)
Returns a {@code NumberFormat} for formatting and parsing numbers for the specified locale.

param
locale the locale to use.
return
a {@code NumberFormat} for handling {@code Number} objects.
since
Android 1.0

        return getInstance(locale, "Number"); //$NON-NLS-1$
    
static java.lang.StringgetPattern(java.util.Locale locale, java.lang.String type)

        ResourceBundle bundle = getBundle(locale);
        return bundle.getString(type);
    
public static final java.text.NumberFormatgetPercentInstance()
Returns a {@code NumberFormat} for formatting and parsing percentage values for the default locale.

return
a {@code NumberFormat} for handling percentage values.
since
Android 1.0

        return getPercentInstance(Locale.getDefault());
    
public static java.text.NumberFormatgetPercentInstance(java.util.Locale locale)
Returns a {@code NumberFormat} for formatting and parsing percentage values for the specified locale.

param
locale the locale to use.
return
a {@code NumberFormat} for handling percentage values.
since
Android 1.0

        return getInstance(locale, "Percent"); //$NON-NLS-1$
    
public inthashCode()

        return (groupingUsed ? 1231 : 1237) + (parseIntegerOnly ? 1231 : 1237)
                + maximumFractionDigits + maximumIntegerDigits
                + minimumFractionDigits + minimumIntegerDigits;
    
public booleanisGroupingUsed()
Indicates whether this number format formats and parses numbers using a grouping separator.

return
{@code true} if a grouping separator is used; {@code false} otherwise.
since
Android 1.0

        return groupingUsed;
    
public booleanisParseIntegerOnly()
Indicates whether this number format only parses integer numbers. Parsing stops if a decimal separator is encountered.

return
{@code true} if this number format only parses integers, {@code false} if if parsese integers as well as fractions.
since
Android 1.0

        return parseIntegerOnly;
    
public java.lang.Numberparse(java.lang.String string)
Parses a {@code Number} from the specified string using the rules of this number format.

param
string the string to parse.
return
the {@code Number} resulting from the parsing.
exception
ParseException if an error occurs during parsing.
since
Android 1.0

        ParsePosition pos = new ParsePosition(0);
        Number number = parse(string, pos);
        if (pos.getErrorIndex() != -1 || pos.getIndex() == 0) {
            throw new ParseException(null, pos.getErrorIndex());
        }
        return number;
    
public abstract java.lang.Numberparse(java.lang.String string, java.text.ParsePosition position)
Parses a {@code Number} from the specified string starting at the index specified by {@code position}. If the string is successfully parsed then the index of the {@code ParsePosition} is updated to the index following the parsed text. On error, the index is unchanged and the error index of {@code ParsePosition} is set to the index where the error occurred.

param
string the string to parse.
param
position input/output parameter, specifies the start index in {@code 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.
return
the {@code Number} resulting from the parse or {@code null} if there is an error.
since
Android 1.0

public final java.lang.ObjectparseObject(java.lang.String string, java.text.ParsePosition position)

        if (position == null) {
            // text.1A=position is null
            throw new NullPointerException(Messages.getString("text.1A")); //$NON-NLS-1$
        }

        try {
            return parse(string, position);
        } catch (Exception e) {
            return null;
        }
    
private voidreadObject(java.io.ObjectInputStream stream)

        ObjectInputStream.GetField fields = stream.readFields();
        groupingUsed = fields.get("groupingUsed", true); //$NON-NLS-1$
        parseIntegerOnly = fields.get("parseIntegerOnly", false); //$NON-NLS-1$
        if (fields.get("serialVersionOnStream", 0) == 0) { //$NON-NLS-1$
            maximumFractionDigits = fields.get("maxFractionDigits", (byte) 3); //$NON-NLS-1$
            maximumIntegerDigits = fields.get("maxIntegerDigits", (byte) 40); //$NON-NLS-1$
            minimumFractionDigits = fields.get("minFractionDigits", (byte) 0); //$NON-NLS-1$
            minimumIntegerDigits = fields.get("minIntegerDigits", (byte) 1); //$NON-NLS-1$
        } else {
            maximumFractionDigits = fields.get("maximumFractionDigits", 3); //$NON-NLS-1$
            maximumIntegerDigits = fields.get("maximumIntegerDigits", 40); //$NON-NLS-1$
            minimumFractionDigits = fields.get("minimumFractionDigits", 0); //$NON-NLS-1$
            minimumIntegerDigits = fields.get("minimumIntegerDigits", 1); //$NON-NLS-1$
        }
        if (minimumIntegerDigits > maximumIntegerDigits
                || minimumFractionDigits > maximumFractionDigits) {
            // text.00=min digits greater than max digits
            throw new InvalidObjectException(Messages.getString("text.00")); //$NON-NLS-1$
        }
        if (minimumIntegerDigits < 0 || maximumIntegerDigits < 0
                || minimumFractionDigits < 0 || maximumFractionDigits < 0) {
            // text.01=min or max digits negative
            throw new InvalidObjectException(Messages.getString("text.01")); //$NON-NLS-1$
        }
    
public voidsetCurrency(java.util.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 {@code UnsupportedOperationException}, concrete subclasses should override this method if they support currency formatting.

param
currency the new currency.
throws
UnsupportedOperationException
since
Android 1.0

        throw new UnsupportedOperationException();
    
public voidsetGroupingUsed(boolean value)
Sets whether this number format formats and parses numbers using a grouping separator.

param
value {@code true} if a grouping separator is used; {@code false} otherwise.
since
Android 1.0

        groupingUsed = value;
    
public voidsetMaximumFractionDigits(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.

param
value the maximum number of fraction digits.
since
Android 1.0

        maximumFractionDigits = value < 0 ? 0 : value;
        if (maximumFractionDigits < minimumFractionDigits) {
            minimumFractionDigits = maximumFractionDigits;
        }
    
public voidsetMaximumIntegerDigits(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.

param
value the new maximum number of integer numerals for display.
since
Android 1.0

        maximumIntegerDigits = value < 0 ? 0 : value;
        if (maximumIntegerDigits < minimumIntegerDigits) {
            minimumIntegerDigits = maximumIntegerDigits;
        }
    
public voidsetMinimumFractionDigits(int value)
Sets the minimum number of fraction digits that are printed when formatting.

param
value the minimum number of fraction digits.
since
Android 1.0

        minimumFractionDigits = value < 0 ? 0 : value;
        if (maximumFractionDigits < minimumFractionDigits) {
            maximumFractionDigits = minimumFractionDigits;
        }
    
public voidsetMinimumIntegerDigits(int value)
Sets the minimum number of integer digits that are printed when formatting.

param
value the minimum number of integer digits.
since
Android 1.0

        minimumIntegerDigits = value < 0 ? 0 : value;
        if (maximumIntegerDigits < minimumIntegerDigits) {
            maximumIntegerDigits = minimumIntegerDigits;
        }
    
public voidsetParseIntegerOnly(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 {@code true} value then subsequent parsing attempts will stop if a decimal separator is encountered.

param
value {@code true} to only parse integers, {@code false} to parse integers as well as fractions.
since
Android 1.0

        parseIntegerOnly = value;
    
private voidwriteObject(java.io.ObjectOutputStream stream)

 //$NON-NLS-1$

          
        ObjectOutputStream.PutField fields = stream.putFields();
        fields.put("groupingUsed", groupingUsed); //$NON-NLS-1$
        fields
                .put(
                        "maxFractionDigits", //$NON-NLS-1$
                        maximumFractionDigits < Byte.MAX_VALUE ? (byte) maximumFractionDigits
                                : Byte.MAX_VALUE);
        fields.put("maximumFractionDigits", maximumFractionDigits); //$NON-NLS-1$
        fields.put("maximumIntegerDigits", maximumIntegerDigits); //$NON-NLS-1$
        fields
                .put(
                        "maxIntegerDigits", //$NON-NLS-1$
                        maximumIntegerDigits < Byte.MAX_VALUE ? (byte) maximumIntegerDigits
                                : Byte.MAX_VALUE);
        fields
                .put(
                        "minFractionDigits", //$NON-NLS-1$
                        minimumFractionDigits < Byte.MAX_VALUE ? (byte) minimumFractionDigits
                                : Byte.MAX_VALUE);
        fields.put("minimumFractionDigits", minimumFractionDigits); //$NON-NLS-1$
        fields.put("minimumIntegerDigits", minimumIntegerDigits); //$NON-NLS-1$
        fields
                .put(
                        "minIntegerDigits", //$NON-NLS-1$
                        minimumIntegerDigits < Byte.MAX_VALUE ? (byte) minimumIntegerDigits
                                : Byte.MAX_VALUE);
        fields.put("parseIntegerOnly", parseIntegerOnly); //$NON-NLS-1$
        fields.put("serialVersionOnStream", 1); //$NON-NLS-1$
        stream.writeFields();