Java Reference
In-Depth Information
public static NumberFormat getNumberInstance(Locale loc) is used for
formatting and parsing numbers in the given locale.
public static final NumberFormat getCurrencyInstance() returns a currency
format for the default locale.
public static NumberFormat getCurrencyInstance(Locale loc) returns a currency
format for the given locale.
public static final NumberFormat getIntegerInstance() is used for formatting
and parsing integers. Floating-point numbers are rounded using the half-even rounding
mode. (See the Java API documentation for NumberFormat if you are interested in
learning about the half-even rounding mode. It is not a topic you need to know for the
SCJP exam.)
public static NumberFormat getIntegerInstance(Locale loc) returns an integer
format for the given locale.
public static final NumberFormat getPercentInstance() is intended for
formatting and parsing percentages using the default locale.
public static NumberFormat getPercentInstance(Locale loc) returns a
percentage format for the given locale.
Each method is overloaded with a Locale object so that you can use a formatter for a
specifi c locale. The no-argument versions of these methods use the default locale, which
vary depending on the platform that the program executes on. After you obtain a Number-
Format instance, use its format and parse methods to format and parse numbers and cur-
rency. Let's start with a discussion on the format methods.
The NumberFormat.format Methods
Use one of the format methods of the NumberFormat class to format a number. The class
defi nes several overloaded versions of format , including
public final String format(long number)
public final String format(double number)
The format method formats the given number based on the locale associated with the
NumberFormat object. The following code demonstrates using a NumberFormat object with
the German language locale. Study the code and see if you can determine its output:
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
double d = 123.57;
System.out.println(nf.format(d));
If you are not familiar with how numbers are formatted in German, decimal numbers
use a comma instead of a decimal point, so the output is
123,57
Search WWH ::




Custom Search