[英]Parentheses in Java
How can I make Java print a double variable ( discount
) inside of parentheses -eg- (42.00% of your purchase)
? 如何使Java在括号-eg-
(42.00% of your purchase)
)内打印双精度变量( discount
(42.00% of your purchase)
?
When I type System.out.println(discount + "(% of your purchase)");
当我键入
System.out.println(discount + "(% of your purchase)");
the output does not include the variable that discount
holds inside of the parentheses. 输出不包括
discount
在括号内包含的变量。 It outputs 42.00(% of your purchase)
. 它输出
42.00(% of your purchase)
。
System.out.printf("(%.2f%% of your purchase)\n", discount);
Using String formats will help you include the variable in the string, but also format it with how many decimals you want. 使用字符串格式可以帮助您在字符串中包含变量,还可以使用所需的小数位数对其进行格式化。
In this case %%
is a literal percent sign 在这种情况下,
%%
是文字百分号
%.2f
means print the floating number with 2 decimal places. %.2f
表示打印浮点数, %.2f
两位小数。
(If you want more information on String formatting see the official spec here https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#syntax or search around for a Java String Format Tutorial) (如果您想了解有关字符串格式的更多信息,请参见此处的官方规范https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#syntax或搜索Java字符串格式教程)
System.out.println("(" + discount + "% of your purchase)");
System.out.printf("(%f%% of your purchase)", discount);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.