gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:52:30 26 4
gpt4 key购买 nike

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

谢谢

最佳答案

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

System.out.printf(formatString, args)

System.outPrintStream . PrintStream.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() 是一个 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 类。 DecimalFormatNumerFormat两者都有一个 format 方法,该方法采用 double 或 Number 并根据这些类的定义将它们格式化为字符串。据我所知,Formatter 不使用它们。

希望这对您有所帮助。

关于Java 的字符串/数字/货币格式化功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8689293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com