How to print % in Java using String.format
In this tutorial, we are learning how to print % in Java using String.format function.
How to print % in String.format
To print ‘%’ in String.format we need to use two times the’ %’ symbol in the string format parameter. That is ‘%%’.
String s6=String.format("The percentage scored in my exam is %.2f%%",86.92); System.out.println(s6);
The output looks like this:
The percentage scored in my exam is 86.92%
What is the String.format function?
String.format is the most common method for formatting a string in java. It is available in java.lang package and it is a default package that is automatically imported in the java program.
Using String.format function for formatting
String.format takes two parameters.
public static String format(String format,Object args)
- format is for formatting the string
- args is used for specifying the number of arguments
public class StringFormattingDemo { public static void main(String args[]) { String s1=String.format("name is %s","CodeSpeedy"); String s2=String.format("value is %f",92.461248); String s3=String.format("value is %.12f",92.461248); String s4=String.format("value is %32f",92.461248); String s5=String.format("value is %32.12f",92.461248); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); System.out.println(s5); } }
Here, I have Initialized a variable with String.format and in it, the parameters are format and args. In format parameter ‘%’ symbol with an alphabet is called a format specifier. The most common format specifiers are:
- %d -> Integer
- %f -> Float
- %s -> String
- %o -> octal number
- %x -> hexadecimal number
- %c -> Character
The output looks like this:
name is CodeSpeedy value is 92.461248 value is 92.461248000000 value is 92.461248 value is 92.461248000000
Leave a Reply