0

我是一个 java 新手,试图让我的打印输出语句格式化小数位。我知道 %.2f 有效,但是无论出于何种原因,当我尝试应用 %.2f 时它都会爆炸……不知道是什么做..有什么建议吗?提前致谢!

credits = int 

raise = double

System.out.printf("An undergraduate resident student taking " + credits + " currently pays $" + "%,.2f",credtotal);

System.out.println("\n");

System.out.printf("with a increase in tuition of " + (trying to format here) raise + ", per credit will become " + raisecredund +  ", and an undergraduate resident taking " + credits +  " credits" + " will pay $" +"%,.2f",(credits*(raise*245.73))+ credtotal);; 
4

2 回答 2

0
 final String str1 = String.format("An undergraduate resident student taking %d currently pays $%.2f",credits, credtotal);

编辑:我没有注意到你正在使用printf. 你很接近:

 System.out.printf("An undergraduate resident student taking %d currently pays $%.2f", credits,credtotal);

使用您的第一个示例字符串,您提供内联格式字符,然后为每个占位符提供一个参数。假设credtotal是 double 并且知道creditsint,以上将产生(分配了相应的值)

An undergraduate resident student taking 1 currently pays $2.00

请参阅创建格式化字符串部分

于 2013-10-09T20:26:23.397 回答
0

您似乎使用"%,.2f"逗号,我认为这是不合法的。 %.2f将数字打印到小数点后 2 位。

如果你想在 3 个地方包括一个逗号,比如 in money,你应该使用 DecimalFormat
DecimalFormat formatter = new DecimalFormat("#,###.00");

于 2013-10-09T20:26:46.033 回答