System. Out. Format ()
System. Out. printf ()
Format specifiers
% [Argument_index $] [flags] [width] [. Precision] Conversion
Width: controls the minimum size of a field. By default, the data is right aligned, but you can use "-" to change the alignment direction.
Precision: specifies the maximum size.
Width can be applied to various types of data conversion, and its behavior is the same. Precision is not the case. Not all types of data can use precision. In addition, precision has different meanings when applications convert data of different types. When applying precision to string, it indicates the maximum number of characters output when string is promised. When it is used for floating point numbers, it indicates the number of digits to be displayed in the decimal part (6 digits by default). If the number of decimal places is too large, it is rounded. If the number is too small, it is filled with zero at the end. Precision cannot be used as an integer.
//: Strings/receept. javaimport Java. util. *; public class receept {private double Total = 0; private formatter F = new formatter (system. out); Public void printtitle () {f. format ("%-15 S % 5 S % 10s \ n", "item", "QTY", "price"); F. format ("%-15 S % 5 S % 10s \ n", "----", "---", "-----");} public void print (string name, int qty, double price) {f. format ("%-15.15 S % 5d % 10.2f \ n", name, qty, price); Total + = Price ;} Public void printtotal () {f. format ("%-15 S % 5 S % 10.2f \ n", "Tax", "", total * 0.06); F. format ("%-15 S % 5 S % 10s \ n", "-----"); F. format ("%-15 S % 5 S % 10.2f \ n", "Total", "", total * 1.06);} public static void main (string [] ARGs) {receipreceept = new receip(); receip. printtitle (); receept. print ("Jack's magic beans", 4, 4.25); receipt. print ("Princess peas", 3, 5.1); receept. print ("Three Bea RS porridge ", 1, 14.29); receipt. printtotal () ;}/ * output: item qty price ---- ----- Jack's magic be 4 4.25 princess peas 3 5.10 three bears por 1 14.29tax 1.42 ----- total 25.06 *///:~