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



是否有更简单的方法来理解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.formatString.format都使用相同的语法和格式标志。我看不出这三个有什么不同。

谢谢

我会考虑下载相应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,并返回一个包含格式化字符串和参数的格式化结果的新字符串。

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

System.console()ConsoleConsole.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类的数字,有两个具体的格式化器。DecimalFormatNumerFormat都有一个format方法,该方法接受双精度对象或Number,并根据这些类的定义将它们格式化为字符串返回。据我所知,Formatter不使用它们。

最新更新