[英]Java's String/Number/currency formatting capabilities
有沒有更簡單的方法來理解java中的多種格式化方式是如何相關的? 我對以下內容感到困惑:
System.out.printf()
System.out.format()
String.format()
System.console.format()
new Formatter(new StringBuffer("Test")).format();
DecimalFormat.format(value);
NumberFormat.format(value);
以上課程/方法是否相關? 了解差異以及在哪種情況下使用哪種方法最好的方法是什么?
例如, System.out.printf
, System.out.format
和String.format
都使用相同的語法和格式標志。 我不知道他們三個人的區別是什么。
謝謝
我會考慮為您的相應Java版本下載javadocs和源代碼jar,因為通過查看源代碼和文檔可以輕松回答所有問題。
System.out.printf(formatString, args)
System.out
是一個PrintStream
。 PrintStream.printf(formatString, args)
實際上是對PrintStream.format(formatString, args);
的方便方法調用PrintStream.format(formatString, args);
。
System.out.format(formatString, args)
這是對PrintStream.format(formatString, args)
的調用PrintStream.format(formatString, args)
它使用Formatter
結果並將它們附加到PrintStream
。
String.format(formatString, args)
此方法還使用Formatter
並返回帶有格式化字符串和args的格式化結果的新字符串。
System.console().format(formatString, args)
System.console()
是一個Console
。 Console.format(format, args)
使用Formatter
將格式化的字符串顯示到控制台。
new Formatter(new StringBuffer("Test")).format(formatString, args);
這將使用傳入的字符串緩沖區創建Formatter
的實例。如果使用此調用,則必須使用out()
方法來獲取Formatter
寫入的Appendable
。 相反,你可能想做類似的事情:
StringBuffer sb = new StringBuffer("Test");
new Formatter(sb).format(formatString, args);
// now do something with sb.toString()
最后:
DecimalFormat.format(value);
NumberFormat.format(value);
這些是不使用Formatter
類的數字的兩個concreate格式化程序。 DecimalFormat
和NumerFormat
都有一個format
方法,它接受一個double或Number
並根據這些類的定義將它們格式化為字符串。 據我所知, Formatter
不使用它們。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.