Kmags
Kmags

Reputation: 31

Parentheses in Java

How can I make Java print a double variable (discount) inside of parentheses -e.g.- (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).

Upvotes: 1

Views: 1884

Answers (3)

cucaracho
cucaracho

Reputation: 184

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

Upvotes: 1

DeadChex
DeadChex

Reputation: 4629

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)

Upvotes: 4

Allan Lago
Allan Lago

Reputation: 309

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

Upvotes: 1

Related Questions