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

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar