java - 格式化相同数据的方法有很多

这四种格式化相同数据的方式有什么区别吗?

    // Solution 1
    System.out.printf("%.1\n",10.99f);

    // Solution 2
    System.out.format("%.1\n",10.99f);

    // Solution 3
    System.out.print(String.format("%.1\n",10.99f));

    // Solution 4
    Formatter formatter = new Formatter();
    System.out.print(formatter.format("%.1\n",10.99f));
    formatter.close();

最佳答案

前两个完全相同,因为 printf 实现为 ( source )

public PrintStream printf(String format, Object ... args) {
    return format(format, args);
}

后两者也完全相同,因为 String.format 实现为 (source )

public static String format(String format, Object ... args) {
    return new Formatter().format(format, args).toString();
}

最后,第 2 和第 4 大致相同,从 PrintStream.format ( source ) 的实现中可以看出。在引擎盖下,它还创造了一个新的 Formatter(如果需要)并在该 Formatter 上调用 format

public PrintStream format(String format, Object ... args) {
    try {
        synchronized (this) {
            ensureOpen();
            if ((formatter == null)
                || (formatter.locale() != Locale.getDefault()))
                formatter = new Formatter((Appendable) this);
            formatter.format(Locale.getDefault(), format, args);
        }
    } catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    } catch (IOException x) {
        trouble = true;
    }
    return this;
}

https://stackoverflow.com/questions/16583248/

相关文章:

android - EditText 提示随重力消失

css - 防止eclipse破坏CSS格式

awk - 带有 awk 的 pretty-print 表

c# - 支持自定义数字类型的 ToString(字符串格式)

php - 为什么 PHP 回显的文本会丢失其格式?

c# - String.Format 没有正确转换阿拉伯语的整数

javascript - 如何在 Eclipse 的 Javascript 源代码中设置数组元素的缩

python - 在空格或连字符上拆分?

vim - 在 Vim 中将光标移过长的软环绕行

c# - Html.HiddenFor 在 ASP.NET 中错误地格式化 DateTime