简体   繁体   中英

Parentheses in Java

How can I make Java print a double variable ( discount ) inside of parentheses -eg- (42.00% of your purchase) ?

When I type System.out.println(discount + "(% of your purchase)"); the output does not include the variable that discount holds inside of the parentheses. It outputs 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.

(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)

System.out.println("(" + discount + "% of your purchase)");
 System.out.printf("(%f%% of your purchase)", discount);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM