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 ...
Get Java™ Phrasebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.