O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Formatting Output

float hits=3;
											float ab=10;
											String formattedTxt =
											String.format("Batting average: %.3f", hits/ab);

In this phrase, we use the format() method to format an output string that prints a baseball batting average in the standard format of three decimal places. The batting average is defined as the number of hits, divided by the number of at-bats, ab. The format specifier %.3f tells the formatter to print the average as a floating point number with three digits following the decimal point.

JDK1.5 introduced the java.util.Formatter class, which can be used to easily format text. The Formatterclass works very similar to the printf function in the C language, and provides support for layout justification and alignment, common formats ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required