martes, 2 de noviembre de 2021

Printf en Java System.out.printf

Printf en Java System.out.printf

http://mathcenter.oxford.emory.edu/site/cs170/printf/

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

SpecifierOutputExample
 %ba boolean valuetrue or false
 %ca character'a'
 %da decimal (i.e., base 10) integer200
 %fa floating-point number45.4600000
 %ea number in scientific notation4.556000e+01
 %sa string"Java is cool"


No hay comentarios:

Publicar un comentario