Java的字符串/数字/货币格式化功能

时间:2011-12-31 16:47:40

标签: java string formatting

有没有更简单的方法来理解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.printfSystem.out.formatString.format都使用相同的语法和格式标记。我不知道他们三个人的区别是什么。

由于

1 个答案:

答案 0 :(得分:4)

我会考虑下载相应Java版本的javadocs和源代码jar,因为通过查看源代码和文档可以轻松回答所有问题。

System.out.printf(formatString, args)

System.outPrintStreamPrintStream.printf(formatString, args)实际上是对PrintStream.format(formatString, args);的便捷方法调用。

System.out.format(formatString, args)

这是对PrintStream.format(formatString, args)的来电,使用Formatter格式化结果并将其附加到PrintStream

String.format(formatString, args)

此方法还使用Formatter并返回一个新字符串,其中包含格式字符串和args的格式化结果。

System.console().format(formatString, args)

System.console()ConsoleConsole.format(format, args)使用Formatter向控制台显示格式化字符串。

new Formatter(new StringBuffer("Test")).format(formatString, args);

这会使用传入的字符串缓冲区创建Formatter的实例。如果您使用此调用,则必须使用out()方法来获取Appendable Formatter。相反,你可能想做类似的事情:

StringBuffer sb = new StringBuffer("Test");
new Formatter(sb).format(formatString, args);
// now do something with sb.toString()

最后:

DecimalFormat.format(value);
NumberFormat.format(value);

这些是用于使用Formatter类的数字的两个混合格式化程序。 DecimalFormatNumerFormat都有一个format方法,它取一个double或Number并根据这些类的定义将它们格式化为字符串。据我所知,Formatter不使用它们。

希望这有帮助。

相关问题