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

You have a choice to make when you want to format numbers:

Quick and Dirty Formatting

Java SE 5 introduced a format facility that greatly simplifies the task of formatting your output. There methods, defined by java.io.PrintStream (in the API reference documentation), include the following signatures:
public PrintStream format(String format, Object... args)
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 contains plain text as well as special format specifiers. The format specifiers are special characters that format the arguments of Object... args. (The notation Object... args is a Java SE 5 syntax called varargs, which means that the number of arguments may vary.)

The formatter uses symbols to specify how the resulting string should look. A format symbol is created by prefixing % with any optional characters (such as "," to indicate thousands separation), followed by a letter that represents the desired data output. Here is the simplest example:

int i = 461012;
System.out.format("%d%n", i);
The %d tells the formatter that the argument is a decimal integer. The %n generates a newline. You should always use %n (rather than \n, for example) — this ensures that your output will use the line separator appropriate to the platform running the application. To obtain the actual line separator character(s) for the current platform, use System.getProperty("line.separator").

The following code snippet shows some of what you can do with Formatter:

long n = 461012;
System.out.format("%d%n", n);
System.out.format("%08d%n", n);
System.out.format("%+8d%n", n);
System.out.format("%,8d%n", n);
System.out.format("%+,8d%n%n", n);

double pi = Math.PI;
System.out.format("%f%n", pi);
System.out.format("%.3f%n", pi)
System.out.format(Local.FRANCE, "%s,10.3f%n%n", pi * 1000);

Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c);
System.out.format("%tl:%tM%tp%n", c, c, c);
System.out.format("%dD%n", c);
The output for the previous code is (the quotes are there to delimit the output string and are not part of the actual output):
"461012"
"00461012"
"+461012"
"461,012"
"+461,012"

"3.141593"
"3.142"
"3,141,593"

"July 9, 1959"
"11:52pm"
"07/09/59"

It is beyond the scope of this tutorial to cover the extensive features supported by the Formatter API. For more information, consult the Formatter (in the API reference documentation) class specification.

Formatting with NumberFormat

If you are internationalizing your application, you'll want to use NumberFormat, part of the Internationalization (in the Learning the Java Language trail) facilities. NumberFormat (and the related DecimalFormat classes) understands how to format numbers and currencies in a locale-specific way.

You previously saw how the Formatter API is used to format a number with commas to indicate thousands separators; NumberFormat also supports this ability. The following code snippet 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 = 345987.246;
NumberFormat numberFormatter;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance();
amountOut = numberFormatter.format(amount);
System.out.format("%s%n", 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 Internationalization (in the Learning the Java Language 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.format("%s%n", currencyOut);

The last line of code prints $9,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.format("%s%n", percentOut);
The last line of code prints 75%.

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.