Java – How to display % in String.Format?

This example shows you how to display a percentage % in String.format.

JavaStringFormat1.java

package com.mkyong;

public class JavaStringFormat1 {

    public static void main(String[] args) {

        String result = String.format("%d%", 100);

        System.out.println(result);

    }

}

Output


Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '%'
	at java.base/java.util.Formatter.checkText(Formatter.java:2732)
	at java.base/java.util.Formatter.parse(Formatter.java:2718)
	at java.base/java.util.Formatter.format(Formatter.java:2655)
	at java.base/java.util.Formatter.format(Formatter.java:2609)
	at java.base/java.lang.String.format(String.java:2897)

Solution

To display or escape a single %, we need to put two %%.

JavaStringFormat2.java

package com.mkyong;

public class JavaStringFormat2 {

    public static void main(String[] args) {

        String result = String.format("%d%%", 100); // 100%

        System.out.println(result);

    }

}

Output


100%

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments