Java Reference
In-Depth Information
Formatting Numbers
Problem
You need to format numbers.
Solution
Use a
NumberFormat
subclass.
Java did not originally provide C-style
printf
/
scanf
functions because they tend to mix to-
gether formatting and input/output in a very inflexible way. Programs using
printf
/
scanf
can
be hard to internationalize, for example. Of course, “by popular demand,” Java did eventu-
ally introduce
printf()
, which along with
String.format()
is now standard in Java; see
Java has an entire package,
java.text
, full of formatting routines as general and flexible as
anything you might imagine. As with
printf
, it has an involved formatting language, de-
scribed in the javadoc page. Consider the presentation of long numbers. In North America,
the number one thousand twenty-four and a quarter is written 1,024.25, in most of Europe it
is 1 024,25, and in some other part of the world it might be written 1.024,25. Not to mention
how currencies and percentages are formatted! Trying to keep track of this yourself would
drive the average small software shop around the bend rather quickly.
Fortunately, the
java.text
package includes a
Locale
class, and, furthermore, the Java
runtime automatically sets a default
Locale
object based on the user's environment; (on the
Macintosh and Windows, the user's preferences, and on Unix, the user's environment vari-
ables). (To provide a nondefault locale, see
Using a Particular Locale
.) To provide formatters
customized for numbers, currencies, and percentages, the
NumberFormat
class has static
fact-
ory methods
that normally return a
DecimalFormat
with the correct pattern already instanti-
ated. A
DecimalFormat
object appropriate to the user's locale can be obtained from the fact-
ory method
NumberFormat.getInstance()
and manipulated using
set
methods. Surpris-
ingly, the method
setMinimumIntegerDigits()
turns out to be the easy way to generate a
number format with leading zeros. Here is an example:
public
public class
NumFormat2
{
/** A number to format */
public
class
NumFormat2
public static
static final
final
double
double
data
[] = {