(用Java printf格式字符串

时间:2017-11-05 03:52:47

标签: 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

3 个答案:

答案 0 :(得分:3)

您没有查看Java参考资料。为 Java 格式字符串语法引用docs

Flag ... Description
...
'('      The result will enclose negative numbers in parentheses

答案 1 :(得分:0)

它是一种合法的格式,但很少使用,我们可以找到它的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)"

答案 2 :(得分:-3)

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

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

十进制数:%d

单个字符:%c