(在 Java printf 格式字符串中


public class MyClass {
    public static void main(String args[]) {
        double x=2345.6789;
        System.out.printf("My number is %(f",x);
    }
}
无论出于

何种原因,单括号正在编译和执行,尽管无论我找到多少 printf 引用,都没有将其列为修饰符。 有谁知道为什么这有效或与此类似的情况?

以上代码的输出:

My number is 2345.678900

你没有看Java参考。引用 Java 格式字符串语法的文档:

Flag ... Description
...
'('      The result will enclose negative numbers in parentheses
它是一种

合法的格式,但很少使用,我们可以找到它的Javadoc描述:

 // The '(' numeric flag may be used to format negative numbers with
 // parentheses rather than a minus sign.  Group separators are
 // automatically inserted.
 formatter.format("Amount gained or lost since last statement: $ %(,.2f",
                  balanceDelta);
 // -> "Amount gained or lost since last statement: $ (6,217.58)"

printf 语句中 "%" 和 "f" 之间的圆括号是不必要的。

要表示浮点数,语法为 %f

十进制数:%d

单个字符:%c

最新更新