The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Formatting Numbers

The toString method is handy for simple conversions, but you might not like the format of its output. For instance, a floating-point number that represents a monetary value in your program should perhaps be formatted with only two decimal points. To get more control over the format of the output of your program, you can use the NumberFormat (in the API reference documentation) class and its subclass DecimalFormat (in the API reference documentation), to format primitive-type numbers, such as double, and their corresponding wrapper objects, such as Double. The NumberFormat and DecimalFormat classes are in the java.text package.

The following code example formats a Double. The getNumberInstance method is a factory method that returns an instance of NumberFormat. The format method accepts the Double as an argument and returns the formatted number in a string:

Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance();
amountOut = numberFormatter.format(amount);
System.out.println(amountOut);
The last line of code prints 345,987.246.

Note: The output you see when you run the previous code snippet might be different from that shown because the NumberFormat and the DecimalFormat classes are locale-sensitive—they tailor their output according to locale. A locale is an object that identifies a specific geographical, political, or cultural region. The locale is not explicitly set in the previous code snippet; thus, the number format object uses the default locale for the current invocation of the Java VM. The output shown here is the output you get when the default locale specifies the United States. You can use the Locale.getDefault method to figure out what the current default locale is, and you can use Locale.setDefault to change it.

An alternative to changing the default locale for the current invocation of the Java VM is to specify the locale when you create a number format object. Instead of using the default locale, the number format object uses the one specified when it was created. Here’s how you would create a number format object that tailors its output for France: NumberFormat numberFormatter = NumberFormat.getNumberInstance(Locale.FRANCE); This note applies to all the format examples, including those that use the DecimalFormat class, in the rest of this section. For more information, refer to the internationalization trail.


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.

This code example shows how to format currency:

Double currency = new Double(9876543.21);
NumberFormat currencyFormatter;
String currencyOut;

currencyFormatter = NumberFormat.getCurrencyInstance();
currencyOut = currencyFormatter.format(currency);
System.out.println(currencyOut);

The last line of code prints ,876,543.21.

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%.

The following code sample shows how to format a percentage.

Double percent = new Double(0.75);
NumberFormat percentFormatter;
String percentOut;

percentFormatter = NumberFormat.getPercentInstance();
percentOut = percentFormatter.format(percent);
System.out.println(percentOut);
The last line of code prints 75%.

Using the printf Facility

JDK 5.0 introduces a printf facility which greatly simplifies the task of formatting your output. The method is defined by java.io.PrintStream (in the API reference documentation), and contains the following signature:
public PrintStream printf(String format, Object... args)
The first argument, format, is a format string specifying how the objects in the second argument, args, are to be formatted. To use this method, you must first understand the format string syntax. Fortunately, the API specification for this class is well-documented.

Simply put, a format string is a String that can contain plain text, plus one or more format specifiers. The format specifiers are special characters which format the arguments of Object... args. The notation Object... args is a 5.0 syntax called varargs, which means that the number of arguments may vary.

The API specification gives the following example:

Calendar c = ...;
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY",c);

The format specifiers should be easy to spot. There are three of them: %1$tm,%1$te, and %1$tY, which all apply to the Calendar object c. The format specifiers for this example break down as follows:

Because the format specifiers all use special characters such as this, which can be difficult to remember, you will need to refer to the API specification for the complete list. Once you get used to using its syntax, you will find the printf method to be extremely convenient.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.