【问题标题】:Java's String/Number/currency formatting capabilitiesJava 的字符串/数字/货币格式化功能
【发布时间】:2011-12-31 16:47:39
【问题描述】:

有没有更简单的方法来理解 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 都使用相同的语法和格式标志。我看不出他们三个有什么区别。

谢谢

【问题讨论】:

  • 它们只是包装Formatter 功能的便捷方法。 (不确定NumberFormat 及其子类如何与之关联,即关系流动的方式。)
  • @Dave 但仍然是一个很好的问题,为什么我们确实有 PrintStream.formatPrintStream.printf - afaik 它们是在同一个版本中添加的并且具有相同的功能。 printf 的 jdocs 甚至状态为:An invocation of this method of the form out.printf(format, args) behaves in exactly the same way as the invocation out.format(format, args)。真是奇怪的复制
  • @Voo 我猜有人添加了所有printf 的东西以使format 功能更符合print/println 等,但这只是一个猜测。由于各种原因,大多数 API 都有一定的重复性——允许不同的风格、不同的意图传达等等。
  • @Dave 是的,我认为那里没有深奥的神秘解释,所以这只是一个见仁见智的问题。我个人尝试在我的 API 中完全避免这些事情——引用 Python 的禅宗 There should be one-- and preferably only one --obvious way to do it.。至少 javadoc 清楚地表明它们是相同的,所以没有人会想知道“区别在哪里?” (至少没有人阅读文档)

标签: java string formatting


【解决方案1】:

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

System.out.printf(formatString, args)

System.out 是一个PrintStreamPrintStream.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 不使用它们。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 2012-03-08
    • 1970-01-01
    相关资源
    最近更新 更多