Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You have a choice to make when you want to format numbers:
- If you are performing fairly straightforward formatting, you should use the
java.util.Formatter
API, introduced in release 5.0. This API provides general-purpose formatting that works for all objects and is very easy to use. There is also built-in support forDate
andCalendar
.- If you are internationalizing your code, use
java.text.NumberFormat
.NumberFormat
has special support for currency and knows how to represent numbers and currency in different locales.Quick and Dirty Formatting
Java SE 5 introduced a format facility that greatly simplifies the task of formatting your output. There methods, defined byjava.io.PrintStream
, include the following signatures:The first argument,public PrintStream format(String format, Object... args) public PrintStream printf(String format, Object... args)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 ofObject... args
. (The notationObject... 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:Theint i = 461012; System.out.format("%d%n", i);%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, useSystem.getProperty("line.separator")
.The following code snippet shows some of what you can do with
Formatter
:
The output for the previous code is (the quotes are there to delimit the output string and are not part of the actual output):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);"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 theFormatter
class specification.Formatting with NumberFormat
If you are internationalizing your application, you'll want to useNumberFormat
, part of the Internationalization facilities.NumberFormat
(and the relatedDecimalFormat
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 adouble
. ThegetNumberInstance
method is a factory method that returns an instance ofNumberFormat
. Theformat
method accepts thedouble
as an argument and returns the formatted number in a string:The last line of code printsdouble amount = 345987.246; NumberFormat numberFormatter; String amountOut; numberFormatter = NumberFormat.getNumberInstance(); amountOut = numberFormatter.format(amount); System.out.format("%s%n", amountOut);345,987.246
.
Note: The output you see when you run the previous code snippet might be different from that shown because theNumberFormat
and theDecimalFormat
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 theLocale.getDefault
method to figure out what the current default locale is, and you can useLocale.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:
This note applies to all the format examples, including those that use theNumberFormat numberFormatter = NumberFormat.getNumberInstance(Locale.FRANCE);DecimalFormat
class, in the rest of this section. For more information, refer to Internationalization.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 callgetCurrencyInstance
to create a formatter. When you invoke theformat
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 theNumberFormat
class to format percentages. To get the locale-specific formatter, invoke thegetPercentInstance
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.
The last line of code printsdouble percent = new double(0.75); NumberFormat percentFormatter; String percentOut; percentFormatter = NumberFormat.getPercentInstance(); percentOut = percentFormatter.format(percent); System.out.format("%s%n", percentOut);75%
.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.