[英]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.