  ## The printf Method

Suppose we want to print to the screen the approximate value of some variable. For example, maybe we have written a program that calculates mortgage payments based on the amount of the loan, the interest rate, payback period, etc... Since the payment amount is a monetary amount, we don't want to display it to the user with more than two decimal places, but retaining the extra precision in the variable might be useful if it is to be used for some other calculation later -- but how do we do that? How do we print just an approximation of a variable's value (to some number of decimal places)?

Interestingly, it is possible to creatively use casting and promotion to print a "double" value with only two decimal places. For example, we might do something similar to the following:

double x = 12.345678;
System.out.println("Number is approximately " + (int) (x * 100) / 100.0);


But this seems a bit "kludgy". Java provides a better way to do the same thing with the "printf" method:

double x = 12.345678;
System.out.printf("Number is approximately %.2f", x);

//prints "Number is approximately 12.35"


#### Syntax

System.out.printf( format, item1, item2, ..., itemK );


Here, "format" is a string to print with "format specifiers" (each consisting of a percent sign and a conversion code) that tell Java where and how to display "item1", "item2", etc... within the string printed.

Example

int n = 100;
int i = 4;
System.out.printf("You completed %d out of %d tasks", i, n);

//prints "You completed 4 out of 100 tasks"


In the example above, the format specifier "%d" tells the printf method to print an integer. The first "%d" encountered in the format string gets replaced by the first argument to printf after the string (i.e., i=4), the second "%d" encountered in the format string gets replaced by the second argument to printf after the string (i.e, n=10), and so on...

Looking at our earlier example again,

double x = 12.345678;
System.out.printf("Number is approximately %.2f", x);

//prints "Number is approximately 12.35"


we now see that the format specifier "%.2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%.3f", x would have been printed rounded to 3 decimal places.

#### Some frequently-used format specifiers

Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal (i.e., base 10) integer 200
%f a floating-point number 45.4600000
%e a number in scientific notation 4.556000e+01
%s a string "Java is cool"