Table of Contents
In this post, we will see how to escape Percent sign in String’s format()
method in java.
Escape Percent Sign in String’s Format Method in Java
String’s format()
method uses percent sign(%
) as prefix of format specifier.
For example:
To use number in String’s format()
method, we use %d
, but what if you actually want to use percent sign in the String.
If you want to escape percent sign in String’s format method, you can use % twice (%%
).
Let’s see with the help of example:
1 2 3 4 5 6 7 8 9 10 11 |
package org.arpit.java2blog; public class EscapePercentSignStringFormat { public static void main(String[] args) { String percentSignStr = String.format("10 out of 100 is %d%%", 10); System.out.println(percentSignStr); } } |
Output:
As you can see, we have used %%
to escape percent symbol in 10%
.
Further reading:
Escape Percent Sign in printf() Method in Java
You can apply same logic in printf method to print percent sign using System.out.printf()
method.
1 2 3 4 5 6 7 8 9 10 |
package org.arpit.java2blog; public class EscapePercentSignStringFormat { public static void main(String[] args) { System.out.printf("10 out of 100 is %d%%", 10); } } |
Output:
That’s all about How to escape percent sign in String’s format method in java.