- When printing values with decimal precision (type float or
type double), it is often useful to be able to specify how many
decimal places should be printed
- Since Java 1.5.0, the C-style printf function has been
available, and it provides an easy way to format decimal precision
- Format of printf calls:
System.out.printf(format string, list of parameters);
- The format string is a string in quotes, with special format symbols
inserted:
- %d specifies an integer
- %c specifies a character
- %s specifies a String
- %f specifies a floating point type
- Consider the format symbols to be "fill-in-the-blanks" spots in the
format string. These are filled in with the list of parameters
- Example:
int numStudents = 25;
char letterGrade = 'A';
double gpa = 3.95;
System.out.printf("There are %d students\n", numStudents);
System.out.printf("Bobby's course grade was %c, and his GPA is %f\n",
letterGrade, gpa);
// The output from this example is:
// There are 25 students
// Bobby's course grade was A, and his GPA is 3.950000
- To specify how many decimal places for the output of a floating point
value, modify the %f symbol in this format:
%.Nf // where N is the number of decimal places to print
- Example:
double gpa = 3.275;
double PI = 3.1415;
System.out.printf("gpa = %.2f", gpa);
System.out.printf("PI = %.3f", PI);
// Output is:
// gpa = 3.28
// PI = 3.142