Today we began covering Section 7.4, dealing with formatting output. We introduced Java’s printf statement, and showed examples of how we can use it to format doubles, ints, and Strings.
First we looked at an example of how a double that is used to represent dollars and cents looks like when just using the println statement that we’ve become familiar with:
double dollars = 24;
double salestax = dollars * 0.0125;
System.out.println("price: " + dollars);
System.out.println("tax: " + salestax);
System.out.println("total: " + (dollars + salestax));
The output looks like this:
price: 24.0
tax: 0.30000000000000004
total: 24.3
We’d like to make sure that exactly two digits are displayed to the right of the decimal point (and three for the tax amount), and so we introduce the printf statement and how it lets us do that
System.out.printf("price: %f \n", dollars);
System.out.printf("price: %.2f \n", dollars);
System.out.printf("tax: %.3f \n", salestax);
Using these statements, we get the following output:
price: 24.000000
price: 24.00
tax: 0.300
We then showed a couple of examples of how to use a printf statement when we want more than one value formatted in the string; the second statement below makes both of the formatted values 10 characters long:
System.out.printf("price: %.2f tax: %.3f \n", dollars, salestax);
System.out.printf("price: %10.2f tax: %10.3f \n", dollars, salestax);
With these statements, we get this output; note the 10 character lengths in the second line of output:
price: 24.00 tax: 0.300
price: 24.00 tax: 0.300
Finally, we showed an example that had us format a 10-character String, left justified, for a name, and a 10-character decimal for the age value:
String name = "Scott";
int age = 16;
System.out.printf("NAME AGE \n");
System.out.printf("==== === \n");
System.out.printf("%-10s %-10d \n", name, age);
The output of this code is below:
NAME AGE
==== ===
Scott 16