You have a problem displaying the %
sign when you want to print a number in percentage format using the printf()
method. Because the %
sign is use as a prefix of format specifiers, you need to escape it if you want to display the %
sign as part of the output string.
To escape the percent sign (%
) you need to write it twice, like %%
. It will print out a single %
sign as part of your printf()
method output. Let see an example in the code snippet below:
package org.kodejava.lang;
public class EscapePercentSignExample {
public static void main(String[] args) {
String format = "The current bank interest rate is %6.2f%%.%n";
System.out.printf(format, 10f);
}
}
In the code snippet above we use the following format %6.2f%%.%n
which can be explained as:
%6.2f
format the number (10f
) as six characters in width, right justified, with two places after decimal point. Thef
conversion character means it accept a float value.%%
will escape the%
sign and print it as part of the output.%n
will print out a new line character.
When you execute the code, it will print:
The current bank interest rate is 10.00%.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024