抛出MissingFormatArgumentException的Java-%。2f格式说明符

时间:2015-04-19 21:37:04

标签: java format-specifiers

我正在尝试在Java程序中使用格式说明符来仅显示我正在打印的double变量的前2位小数。

现在,我打印double的声明是System.out.format("Total = $%.2f" + value);(价值是问题的两倍)。

当我运行我的程序时,它会打印出“Total = $”而没有任何问题,然后立即给出MissingFormatArgumentException

控制台中的完整错误日志:

Total = $Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%.3f'
    at java.util.Formatter.format(Unknown Source)
    at java.io.PrintStream.format(Unknown Source)
    at Account.getBalance(Account.java:21)
    at testAccount.main(testAccount.java:4)

我做错了什么?

1 个答案:

答案 0 :(得分:3)

System.out.print的参数不是("...%.2f" + x),而是("...%.2f", x)

请改为尝试:

System.out.format("Total = $%.2f", value);