The Class DecimalFormat

In this lesson, we will explore how to control the appearance of our numerical output.

Program output so far

Up to now, we have had little control over the format of output from println statements. For example, when we display a real value, the number of places shown after the decimal point is left to the system to choose. Sometimes that is good enough, but other times we always will want a certain number of digits to appear. We’ll look at a class in the Java Class Library that can help you produce the output that you desire.

Formatting output

The class DecimalFormat, in the package java.text of the Java Class Library, allows us to create a pattern that describes the desired format of a real number or an integer. The pattern is a string that we pass to the class’s constructor as its argument. It is composed of the following characters:

  • 0 represents a digit; leading and trailing zeros appear in the output.
  • # represents a digit, but leading and trailing zeros do not appear in the output.
  • % at the beginning or end of the pattern multiplies the value of the entire number by 100 and displays it as a percentage.
  • $ at the beginning of the pattern displays as a dollar sign.
  • - displays as a minus sign.
  • . displays as a decimal point.

After we create an object of type DecimalFormat, we use the object when invoking the method format, passing it the value that we want to format. The result is a string suitable as the argument to println.

Example

In the following program, value is a double variable whose value is 0.1, and the DecimalFormat pattern is "0.000".

Get hands-on with 1200+ tech skills courses.