Home : Course Map : Chapter 5 : Java : Tech : DecimalFormat Class
 File/Package/Import   Demo 1   Demo 2 Access/Visibility final & Constants Static Import Jar Files   Demo 3 Applet Directories 3rd Party Packages CLASSPATH javadoc CodingConventions Exercises
 Supplements Scope Debug Techniques Java Runtime Class Class JVM Instructions 2 JVM Processing pack200
 About JavaTech      Codes List      Exercises      Feedback      References      Resources      Tips      Topic Index      Course Guide      What's New

In many of the demonstration programs used so far, we often find that a simple floating point (FP) operation, such as a divide, can result in a long fraction when we use the default conversion of a double to a String.

Control of the format when converting a numerical value to a string was added in Java 1.1 with the java.text package, which includes the classes:

java.text.Format
java.text.NumberFormat
java.text.DecimalFormat

The primary focus of the classes is dealing with internationalization of output such as deciding whether to use a period or comma for the decimal point depending on the current locale setting.

DecimalFormat will seem somewhat awkward to use for floating point formatting, especially for those who are familiar with the printf function in C. (We discuss an open source Java class that acts similiarly to printf on the next page.) However, at least scientific notation was provided as of Java 1.2.

A format is given by a pattern of symbols. For example, the pattern "0.000" indicates that the number should begin with 0 if it is less than 1.0 and that the number of decimal places will be 3 and padded with 0 if neccessary to reach 3 places.

The pattern "0.###" indicates that the number should begin with 0 if it is less than 1.0 and that the number of decimal places will be up to 3 and padded with blanks if the fraction needs less than 3 places.

An exponential pattern appends "E0" to the right side. So "0.000E0" will result in 3 places in fraction of the mantissa and then the exponent, such as "1.234E10".

See the API specifications for DecimalFormat to find the complete set of formatting pattern symbols.

Formatting

The recipe for formatting a floating point value goes as follows:

1. Create a string pattern such as

String fmt = "0.00#";

2. Create an instance of the DecimalFormat class with this pattern:

DecimalFormat df = new DecimalFormat(fmt);

3. Invoke the format method to create the formatted string:

double q = 10.0/4.0;
String str = df.format(q);
System.out.println("q = "+str);

In this case the resulting string is:

q = 2.50

The DecimalFormat object can be reused for new format patterns by invoking the applyPattern(String format) method.

The following demo program illustrates several format patterns:

DecimalFormatDemo.java

import java.applet.*; //
import java.text.*; //

/** Illustrate use of the DecimalFormat class. **/
public class DecimalFormatDemo extends Applet
{

String fValStr = "test";
public void init () {

double q = 1.0/3.0;

// Define the format pattern in a string
String fmt = "0.000";

// Create a DecimalFormat instance for this format
DecimalFormat df = new DecimalFormat (fmt);

// Create a string from the double according to the
// format
fValStr = df.format (q);

System.out.println ("1.0/3.0 = " + fValStr);

// Can change the format pattern:
df.applyPattern ("0.00000");
fValStr = df.format (q);
System.out.println ("1.0/3.0 = " + fValStr);

// The # symbol indicates trailing blanks
df.applyPattern ("0.######");
fValStr = df.format (1.0/2.0);
System.out.println ("1.0/2.0 = " + fValStr);

df.applyPattern ("0.00E0");
fValStr = df.format (1000.0/3.0);
System.out.println ("1000.0/3.0 = " + fValStr);

df.applyPattern ("0.00E0");
fValStr = df.format (3.0/4567.0);
System.out.println ("3.0/4567.0 = " + fValStr);

// Negative infinity
df.applyPattern ("0.000E0");
fValStr = df.format (-1.0/0.0);
System.out.println ("-1.0/0.0 = " + fValStr);

// NaN
df.applyPattern ("0.000E0");
fValStr = df.format (0.0/0.0);
System.out.println ("0.0/0.0 = " + fValStr);

}

// Paint message in Applet window.
public void paint (java.awt.Graphics g) {

g.drawString (fValStr,20,20);

}

// Can also run this program as an application.
// No windowing needed so just run the applets
// init () function.
public static void main (String [] args) {
DecimalFormatDemo obj = new DecimalFormatDemo ();
obj.init ();
}

} // class DecimalFormatDemo

Output of this program:

1.0/3.0 = 0.333
1.0/3.0 = 0.33333
1.0/2.0 = 0.5
1000.0/3.0 = 3.33E2
3.0/4567.0 = 6.57E-4
-1.0/0.0 = -?
0.0/0.0 = ?

The following applet is an interactive program that allows you to set the number of fractional places for both decimal and scientific formats for a quotient value from factors that you enter.

This program code shows how to assign a given Locale to the format so that, for example, it will follow the US standard and indicates the decimal position with a period instead of a comma.

Besides localization, the program uses several techniques, including various graphics tools and the StringBuffer utililty class, not yet discussed. So examining the code is optional.

The Swing component JFormattedTextField, which came with Java 1.4, provides a text field with the formatting defined by a NumberFormat passed via the constructor. Numbers entered will be automatically formatted according to format. See the references for more information.

References & Web Resources

Latest update Oct.24, 2004

 Tech DecimalFormat   Demo 1   Demo 2 System.out.printf   Demo 3 CJ Format Class   Demo 4   Demo 5 Other Format Tools Immutable Complex Exercises
 Physics Interpolation Integration   Demo 1 Simpson Rule   Demo 2 Exercises
 Part I Part II Part III Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17 18 19 20 21 22 23 24 Supplements 1  2  3  4  5  6  7  8  9  10  11  12 Tech 1  2  3  4  5  6  7  8  9  10  11  12 Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.