You are on page 1of 5

26-1

Lesson 26. Formatting (rounding-off)


One method of rounding off is to use the NumberFormat ( requires import java.text.*; ) class to
create a String, and then convert that String back into the desired primitive number type.
A rounding-off example:
For example, to round 34.982665 to the nearest thousandths:
double d = 34.982665;
NumberFormat fmt = NumberFormat.getNumberInstance( );
fmt.setMaximumFractionDigits(3);
fmt.setMinimumFractionDigits(3);
String s = fmt.format(d);
System.out.println(s); //34.983
double d3 = Double.parseDouble(s); //Convert to a double for demo purposes
System.out.println(d3); //34.983 Perfect, just the answer we expected!
Analyzing the details:
Lets examine four important details about the above code:
1. fmt.setMaximumFractionDigits(3) gives us no more than 3 decimal places i.e.
it rounds off to 3 decimal places.
2. fmt.setMinimumFractionDigits(3) guarantees at least 3 decimal places. For
example, if we round off 34.9997 to 3 decimal places we would ordinarily get
35.0; however, with setMinimumFractionDigits(3) we would get 35.000.
3. fmt.format(d) returns a String, not a numeric.
4. You may ultimately want a numeric instead of a String, hence the
Double.parseDouble(s) part of the code.
More NumberFormat objects:
Notice above that the way we create a NumberFormat object is by calling the
getNumberInstance static method. It returns a NumberFormat object. There are two other
similar methods that return NumberFormat objects. These are detailed below along with
sample usage.
1. The object returned by getCurrencyInstance is used for formatting money.
NumberFormat nf = NumberFormat.getCurrencyInstance( );
String str = nf.format(81.09745);
System.out.println(str); //$81.10
str = nf.format(.358);
System.out.println(str); //$.36

26-2
2. The object returned by getPercentInstance is used for formatting percents. The
number to be formatted is multiplied by 100 and then a percent sign is appended.
The settings determined by setMinimumFractionDigits( ) and
setMaximumFractionDigits( ) are applied after multiplication by 100. If these
methods are not specifically called, then their settings are automatically 0.
NumberFormat nf = NumberFormat.getPercentInstance( );
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String str = nf.format(.35838);
System.out.println(str); //35.84%
For even more formatting flexibility use the DecimalFormat class. Its usage is detailed in
Appendix Z. There, you will learn, for example, to specify a pattern like #,###.000, and then
format a number like 3847.2 as 3,847.200.

The Formatter Class:


The Formatter class (new to Java 5.0) is used to format numbers (and other data, too) and
to produce Strings containing the formatted data. Begin the process by creating a
Formatter object:
Formatter fmt = new Formatter( );
Actual formatting is done with the format method. It has several parameters, the first of
which is a String with embedded format specifiers. This is followed by a corresponding
sequence of data to be formatted. The sequence of embedded specifiers matches the
sequence of data parameters as illustrated by the following example:
%f means floating point

fmt.format(My number>>>%f, and my string>>>%s, 237.647, hello);


%s means String

Finally, produce the formatted String with fmt.toString( ) and get:


My number>>>237.647000, and my string>>>hello
In this example we formatted a floating-point number using %f and a String using %s.
See Appendix AD for other format specifiers.
Minimum Field Width:
The output above is especially useful when we are able to specify a field width as in the
next example where we allocate a width of 15 characters to the number and a width of 8
characters to the String. Each field is padded with spaces to insure it occupies the
specified number of characters. If the String or number is longer than the setting, it will
still be printed in its entirety.
fmt.format(My number>>>%15f, and my string>>>%8s, 237.647, hello);

26-3
A subsequent application of fmt.toString( ) will yield (notice the padding with spaces):
My number>>>

237.647000, and my string>>>


15 characters

hello
8 characters

The ability to set field widths is especially useful in the printing of tables since it helps
keep columns aligned.
Precision:
Next, we examine the notion of precision (typically, the number of decimal places). The
precision specifier follows the minimum field width specifier (if there is one) and
consists of a period followed by an integer. It can be applied to %f, %e, %g, or %s. The
default precision for numerics is 6 decimal places.
The following examples show how to use the precision specifier:
1. Example 1 %9.3f a decimal floating point number in a field 9 characters
wide and having 3 decimal places 187.9207 formats as 187.921
2. Example 2 %9.2e a scientific notation number in a field 9 characters wide
and having 2 decimal places 46238.123 formats as 4.62e+04
3. Example 3 %.4g either a decimal floating number or scientific notation
(whichever is shorter) having no minimum field width and having 4 significant
digits. 187.0853211 formats as 187.1
4. Example 4 %6.8s displays a String of at least 6 but not exceeding 8
characters long. If the String is longer than the maximum, characters toward the
end of the String will be truncated abc formats as
abc;
123456789A formats as 12345678
Format Flags:
It is possible to use special format flags to control various aspects of formatting. These
flags immediately follow the %. Some of the more often used flags are detailed here (see
Appendix AD for a more complete list):
- Left justification %-9.2f 72.45822 formats as 72.46

0 Pad with zeros instead of the default spaces %09.2f 72.45822 formats as
000072.46
, Numeric values include grouping separators %-,10.2f1726.46 formats as
1,726.46
It is possible to pass a Formatter object as an argument to the println method where its
toString method is automatically called with System.out.println(fmt);
An even handier shortcut is to dispense with the Formatter object entirely and use the
printf method (new to Java 5.0). The parameters in the example below are exactly the
same as for Formatter.

26-4
System.out.printf(One number, %0,10.2f, followed by another, %-9e, %s,
1267.657, 56.71, number.);
The output is:
One number, 001,267.66, followed by another, 5.671000e+01, number.

Exercise on Lesson 26
1. Using the NumberFormat class, write code that will create a double called cv, assign it a
value of 18.7713, and then convert it to a String rounded off to the nearest hundredth.
Assure that at least 1 decimal place is printed. Print the String.
2. What type variable is returned by the format( ) method of the NumberFormat class?
3. Using the NumberFormat class, write code that will create a double called dv, assign it a
value of 184.767123, and then convert it to a String rounded off to the nearest
thousandth. Assure that at least 2 decimal places are printed.
4. Using the NumberFormat class, write code that will input a double called db from the
keyboard and then convert it to a String in which there are at least 3 decimal places and
at most 4.
5. Assume you already have a floating type variable mn that you want to display as dollars
and cents (example, $127.15). Using the NumberFormat class, write code that will
produce such a printout (including the dollar sign).
6. What import does the NumberFormat class require?
7. What is the output of the following code?
NumberFormat nf = NumberFormat.getCurrencyInstance( );
System.out.println(nf.format(487.0871));
8. What is the output of the following code?
NumberFormat nf = NumberFormat.getPercentInstance( );
nf.setMinimumFractionDigits(3);
nf.setMaximumFractionDigits(3);
String str = nf.format(4.708832);
System.out.println(str);

26-6

Project BaseClass (Shell)


We will create a generic class (sometimes called a shell) for reading/processing files that also
includes a NumberFormat object as well as StringTokenizer and Scanner objects. We will call
this class BaseClass and every time we have a programming project that requires file input, we
will begin by simply pasting in this code. We would then change the name of the class from
BaseClass to whatever the new class name is to be and finally, lay in the additional code to
accomplish the task at hand.
import java.io.*; //necessary for File and IOException
import java.util.*; //necessary for StringTokenizer and Scanner
import java.text.*; //necessary for NumberFormat
public class BaseClass
{
public static void main( String args[] ) throws IOException
{
NumberFormat fmt = NumberFormat.getNumberInstance( );
fmt.setMinimumFractionDigits(3); //may need to change value
fmt.setMaximumFractionDigits(3); //may need to change value
Scanner sf = new Scanner(new File("c:\\temp_Name\\FileName.in"));
int maxIndx = -1; //-1 so when we increment below, the first index is 0
String text[] = new String[1000]; //To be safe, declare more than we need
while(sf.hasNext( ))
{
maxIndx++;
text[maxIndx] = sf.nextLine( );
//System.out.println(text[maxIndx]); //Remove rem for testing
}
//maxIndx is now the highest index of text[]. Equals -1 if no text lines
sf.close( ); //We opened a file above, so close it when finished.
//System.exit(0); //Use this for testing to temporarily end the program here
for (int j = 0; j <= maxIndx; j++)
{
//Typically, only one of the following two will be used.
//StringTokenizer st = new StringTokenizer( text[j] );
//Scanner sc = new Scanner(text[j]);
//code specific to the task
//System.out.println(text[j]); //Remove rem for testing
}
}
}

You might also like