java中格式化輸出字元

來源:互聯網
上載者:User

System.out.format()

System.out.printf()

格式化說明符

%[argument_index$][flags][width][.precision] conversion

width:控制一個域的最小尺寸,在預設情況下,資料是靠右對齊的,不過可以使用"-"來改變對齊方向

precision:指明最大尺寸

width可以應用於各種類型的資料轉換,並且其行為方式都一樣。precision則不然,不是所有類型的資料都能使用precision,而且,應用與不同類型的資料轉換時,precision的意義也不同。在將precision應用與String時,它表示答應String時輸出字元的最大數量。而用於浮點數時,它表示小數部分要顯示出來的位元(預設是6位),如果小數位元過多則舍入,太少則末尾補零。precision無法用於整數。

//: strings/Receipt.javaimport java.util.*;public class Receipt {  private double total = 0;  private Formatter f = new Formatter(System.out);  public void printTitle() {    f.format("%-15s %5s %10s\n", "Item", "Qty", "Price");    f.format("%-15s %5s %10s\n", "----", "---", "-----");  }  public void print(String name, int qty, double price) {    f.format("%-15.15s %5d %10.2f\n", name, qty, price);    total += price;  }  public void printTotal() {    f.format("%-15s %5s %10.2f\n", "Tax", "", total*0.06);    f.format("%-15s %5s %10s\n", "", "", "-----");    f.format("%-15s %5s %10.2f\n", "Total", "",      total * 1.06);  }  public static void main(String[] args) {    Receipt receipt = new Receipt();    receipt.printTitle();    receipt.print("Jack's Magic Beans", 4, 4.25);    receipt.print("Princess Peas", 3, 5.1);    receipt.print("Three Bears Porridge", 1, 14.29);    receipt.printTotal();  }} /* Output:Item              Qty      Price----              ---      -----Jack's Magic Be     4       4.25Princess Peas       3       5.10Three Bears Por     1      14.29Tax                         1.42                           -----Total                      25.06*///:~

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.