- Home
- Objectives

- XyzWs Study Guides
- Study Guides
- Study Notes
- Resources

- Mock Exams
SCJP Study Guide:
API Contents
Printer-friendly version |
Mail this to a friend
NumberFormat
java.text.NumberFormat is 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.
The abstract NumberFormat class uses a factory design pattern to provide instances of itself. Instead of calling its constructors directly (impossible since NumberFormat is an abstract class), you should use one of its static "get???Instance()" creation methods. The names of the different creation methods provide a hint as to how the object should be used. NumberFormat provides three differrent formats: general numbers, currency, and percentages.
After creating a NumberFormat object, you can use one of the many format() methods to create a textual representation of an actual number. Although there are many different overriden versions of this method, they do the same thing; they create a String or append characters to a StringBuffer. To format a number for the current Locale, use one of the factory class methods:
String 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);
Parsing text to create a number is the opposite function of creating a formatted text representation of a number. The NumberFormat method parse() should always be able to create a number from any text created by method format().
The parse() method can be used to create a number from a string of text that a user has entered into a text field:
Number myNumber = nf.parse(myString);
Formatting Numbers
Programs stored and operate on numbers in a locale-independent way. Displaying and printing a number to a String that is in a locale-sensitive format.
To get a NumberFormat instance for the current Locale, use one of the factory class methods:
- public static final NumberFormat getInstance() returns a general-purpose number format for the current default locale. This is the same as calling getNumberInstance().
- public static final NumberFormat getNumberInstance() returns a general-purpose number format for the current default locale.
- public static final NumberFormat getIntegerInstance() returns an integer number format for the current default locale. The returned number format is configured to round floating point numbers to the nearest integer using IEEE half-even rounding (see ROUND_HALF_EVEN) for formatting, and to parse only the integer part of an input string (see isParseIntegerOnly).
To get a NumberFormat instance for a different Locale, use one of the factory class methods:
- public static NumberFormat getInstance(Locale inLocale) returns a general-purpose number format for the specified locale. This is the same as calling getNumberInstance(inLocale).
- public static NumberFormat getNumberInstance(Locale inLocale) returns a general-purpose number format for the specified locale.
- public static NumberFormat getIntegerInstance(Locale inLocale) returns an integer number format for the specified locale. The returned number format is configured to round floating point numbers to the nearest integer using IEEE half-even rounding (see ROUND_HALF_EVEN) for formatting, and to parse only the integer part of an input string (see isParseIntegerOnly).
Use getInstance or getNumberInstance to get the normal
number format. Use getIntegerInstance to get an integer number
format.
Although getInstance and getNumberInstance may
look different, they actually have the same behavior and return the same type
of NumberFormat. Use either one; they do the same thing, which is return a
format object that can be used to format integer or decimal numbers. Each of
these methods have two forms, one that returns a format for the default Locale
and one that allows you to specify a Locale.
public class FormatNumberDemo {
public static void main(String[] args) {
double quantity = 12345.678;
NumberFormat defaultNF = NumberFormat.getNumberInstance();
System.out.println("Default : " + defaultNF.format(quantity));
NumberFormat frenchNF = NumberFormat.getNumberInstance(Locale.FRENCH);
System.out.println("French : " + frenchNF.format(quantity));
NumberFormat germanyNF = NumberFormat.getNumberInstance(Locale.GERMANY);
System.out.println("Germany : " + germanyNF.format(quantity));
}
}
This prints out the following results:
Default : 12,345.678 French : 12 345,678 Germany : 12.345,678
You can also control the display of numbers with such methods as:
- public void setMaximumFractionDigits(int newValue) sets the maximum number of digits allowed in the fraction portion of a number. maximumFractionDigits must be >= minimumFractionDigits. If the new value for maximumFractionDigits is less than the current value of minimumFractionDigits, then minimumFractionDigits will also be set to the new value.
- public int getMaximumFractionDigits() returns the maximum number of digits allowed in the fraction portion of a number.
- public void setMinimumFractionDigits(int newValue) sets the minimum number of digits allowed in the fraction portion of a number. minimumFractionDigits must be <= maximumFractionDigits. If the new value for minimumFractionDigits exceeds the current value of maximumFractionDigits, then maximumIntegerDigits will also be set to the new value.
- public int getMinimumFractionDigits() returns the minimum number of digits allowed in the fraction portion of a number.
- public void setMaximumIntegerDigits(int newValue) sets the maximum number of digits allowed in the integer portion of a number. maximumIntegerDigits must be >= minimumIntegerDigits. If the new value for maximumIntegerDigits is less than the current value of minimumIntegerDigits, then minimumIntegerDigits will also be set to the new value.
- public int getMaximumIntegerDigits() returns the maximum number of digits allowed in the integer portion of a number.
- public void setMinimumIntegerDigits(int newValue) sets the minimum number of digits allowed in the integer portion of a number. minimumIntegerDigits must be <= maximumIntegerDigits. If the new value for minimumIntegerDigits exceeds the current value of maximumIntegerDigits, then maximumIntegerDigits will also be set to the new value.
- public int getMinimumIntegerDigits() returns the minimum number of digits allowed in the integer portion of a number.
public class FractionDigitsDemo {
public static void main(String[] args) {
// Get a default NumberFormat instance.
NumberFormat numForm = NumberFormat.getNumberInstance();
System.out.println("Minimum Fraction Digits : " + numForm.getMinimumFractionDigits());
System.out.println("Maximum Fraction Digits : " + numForm.getMaximumFractionDigits());
// Format some decimals using the pattern supplied above.
String num1 = numForm.format(22.34235D);
System.out.println("num1 = " + num1);
// Set the maximum fraction digits to 2.
numForm.setMaximumFractionDigits(5);
String num2 = numForm.format(22.34235D);
System.out.println("num2 = " + num2);
}
}
This prints out the following results:
Minimum Fraction Digits : 0 Maximum Fraction Digits : 3 num1 = 22.342 num2 = 22.34235
The format() method added a comma for the thousands separator, for example "12,345.678". This is often called a grouping separator. You can control it too,
-
public void setGroupingUsed(boolean newValue) set whether or not grouping will
be used in this format.
public boolean isGroupingUsed()Returns true if grouping is used in this format. For example, in the English locale, with grouping on, the number 1234567 might be formatted as "1,234,567". The grouping separator as well as the size of each group is locale dependant and is determined by sub-classes of NumberFormat.
public class GroupingDemo {
public static void main(String[] args) {
// Get a default NumberFormat instance.
NumberFormat numForm = NumberFormat.getInstance();
numForm.setGroupingUsed(true);
System.out.println("Number = " + numForm.format(1234567));
numForm.setGroupingUsed(false);
System.out.println("Number = " + numForm.format(1234567));
}
}
This prints out the following results:
Number = 1,234,567 Number = 1234567
Formatting Currencies
If you're writing business applications, you'll probably need to format and to
display currencies. You format currencies in the same manner as numbers, except
that you call getCurrencyInstance to create a formatter. When you
invoke the format method, it returns a String that
includes the formatted number and the appropriate currency sign.
To get a currency NumberFormat instance for the current Locale, use one of the factory class methods:
- public static final NumberFormat getCurrencyInstance() creates an instance of a NumberFormat object that can be used to format and parse currency values.
To get a currency NumberFormat instance for a different Locale, use one of the factory class methods:
- public static NumberFormat getCurrencyInstance(Locale inLocale) creates an instance of a NumberFormat object that can be used to format and parse currency values for the given locale. The inLocale object containing the locale that will be used to format and parse the currency value.
public class FormatCurrencyDemo {
public static void main(String[] args) {
// Get a default NumberFormat instance.
NumberFormat currencyorm = NumberFormat.getCurrencyInstance();
// Format some decimals using the pattern supplied above.
String currency1 = currencyForm.format(22.3423D);
System.out.println("currency1 = " + currency1);
// Get a default NumberFormat instance using the
// fr_CA locale.
Locale caLoc = new Locale("fr", "CA");
NumberFormat currencyFormCA =
NumberFormat.getCurrencyInstance(caLoc);
// Format some decimals using the pattern supplied above.
String currency2 = currencyFormCA.format(22.3423D);
System.out.println("currency2 = " + currency2);
}
}
This prints out the following results:
currency1 = $22.34 currency2 = 22,34 $
Formatting Percentages
You can also use the methods of the NumberFormat class to format
percentages. To get the locale-specific formatter, invoke the getPercentInstance
method. With this formatter, a decimal fraction such as 0.75 is displayed as
75%.
To get a percentage NumberFormat instance for the current Locale, use one of the factory class methods:
- public static final NumberFormat getPercentInstance() creates an instance of a NumberFormat object that can be used to format and parse currency values.
To get a percentage NumberFormat instance for a different Locale, use one of the factory class methods:
- public static NumberFormat getPercentInstance(Locale inLocale) creates an instance of a NumberFormat object that can be used to format and parse percentage values for the given locale. The inLocale object containing the locale that will be used to format and parse the percentage value.
public class FormatPercentageDemo {
public static void main(String[] args) {
// Get a default NumberFormat instance.
NumberFormat percentForm = NumberFormat.getPercentInstance();
// Format some decimals using the pattern supplied above.
String percentage1 = percentForm.format(22.3423D);
System.out.println("percentage1 = " + percentage1);
// Get a default NumberFormat instance using the
// es_ES locale.
Locale caLoc = new Locale("es", "ES");
NumberFormat percentFormCA =
NumberFormat.getPercentInstance(caLoc);
// Format some decimals using the pattern supplied above.
String percentage2 = percentFormCA.format(22.3423D);
System.out.println("percentage2 = " + percentage2);
}
}
This prints out the following results:
percentage1 = 2,234% percentage2 = 2.234%
More Methods
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 and DecimalFormat are
designed such that some controls work for formatting and others work for
parsing. The following is the detailed description for each these control
methods:
- public void setParseIntegerOnly(boolean value) sets whether or not numbers should be parsed as integers only.
- public boolean isParseIntegerOnly() returns true if this format will parse numbers as integers only.
For example in the English locale, with ParseIntegerOnly true, the string "3456.78" would be parsed as the integer value 3456 and parsing would stop at the "." character. If ParseIntegerOnly is false, the string "3456.78" would be parsed as vallue 3456.78. This is independent of formatting.Of course, the exact format accepted by the parse operation is locale dependant and determined by sub-classes of NumberFormat.
public class ParseIntegerDemo {
public static void main(String[] args) {
// Get a default NumberFormat instance.
NumberFormat numForm = NumberFormat.getInstance();
try
{
// Parse a decimal value.
Number n = numForm.parse("123456789.14");
System.out.println("Number = " + n);
// Set the parse integer only flag to true.
numForm.setParseIntegerOnly(true);
n = numForm.parse("123456789.14");
System.out.println("Number = " + n);
}
catch (ParseException ex)
{
System.out.println(ex.toString());
}
// Display the various properties of the NumberFormat
// class.
System.out.println("Maximum Fraction Digits: " +
numForm.getMaximumFractionDigits());
System.out.println("Maximum Integer Digits: " +
numForm.getMaximumIntegerDigits());
System.out.println("Minimum Fraction Digits: " +
numForm.getMinimumFractionDigits());
System.out.println("Minimum Integer Digits: " +
numForm.getMinimumIntegerDigits());
System.out.println("Is Grouping Used? " +
numForm.isGroupingUsed());
System.out.println("Is Parse Integer Only? " +
numForm.isParseIntegerOnly());
}
}
This prints out the following results:
Number = 1.2345678914E8 Number = 123456789 Maximum Fraction Digits: 3 Maximum Integer Digits: 2147483647 Minimum Fraction Digits: 0 Minimum Integer Digits: 1 Is Grouping Used? true Is Parse Integer Only? true
If you want to not show a decimal point where there might be no digits after the decimal point, use setDecimalSeparatorAlwaysShown.
setDecimalSeparatorAlwaysShown : only affects formatting, and only where there might be no digits after the decimal point, such as with a pattern like "#,##0.##", e.g., if true, 3456.00 -> "3,456." if false, 3456.00 -> "3456" This is independent of parsing. If you want parsing to stop at the decimal point, use setParseIntegerOnly.
You can also use forms of the parse and format methods
with ParsePosition and 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:
-
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 at 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. 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.
The following example use ParsePosition:
public class ParsePositionDemo {
public static void main(String[] args) {
// Get a default NumberFormat instance.
NumberFormat numForm = NumberFormat.getInstance();
// Parse the decimal starting at position 8.
ParsePosition pos = new ParsePosition(8);
Number n = numForm.parse("123456789.14", pos);
System.out.println("Number = " + n);
System.out.println("Position after parse = " +
pos.getIndex());
// Parse the decimal starting at position 5.
ParsePosition pos1 = new ParsePosition(5);
Object o = numForm.parseObject("123456789.14", pos1);
System.out.println("Number = " + o.toString());
}
}
This prints out the following results:
Number = 9.14 Position after parse = 12 Number = 6789.14
The following example use FiledPosition:
public class ParsePositionDemo {
public static void main(String[] args) {
// Get a default NumberFormat instance.
NumberFormat numForm = NumberFormat.getInstance();
// Format some decimals using the pattern supplied above.
StringBuffer dest1 = new StringBuffer(24);
StringBuffer dest2 = new StringBuffer(24);
FieldPosition pos = new FieldPosition(NumberFormat.FRACTION_FIELD);
dest1 = numForm.format(22.3423D, dest1, pos);
System.out.println("dest1 = " + dest1);
System.out.println("FRACTION is at: " + pos.getBeginIndex() +
", " + pos.getEndIndex());
dest2 = numForm.format(64000D, dest2, pos);
System.out.println("dest2 = " + dest2);
System.out.println("FRACTION is at: " + pos.getBeginIndex() +
", " + pos.getEndIndex());
}
}
This prints out the following results:
dest1 = 22.342 FRACTION is at: 3, 6 dest2 = 64,000 FRACTION is at: 6, 6
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.