We can also format the numbers with thousands-separator using the comma flag. We can limit them by using precision modifiers. By default, %f will add extra zeroes to the output. ("%.3s", "string") //first three characters of the stringĪs discussed above, %d is used to format integers and %f is used to format floating-point numbers. It can also be used to extract substrings. The precision can be used to specify the digits after the decimal point for floating-point numbers. However, the output with padding will look like " '-string' ", where a hyphen denotes an empty space. The output for the above code will simply be the word "string". Consider the following example to better understand it. If the value to be printed has a smaller length then padding would be added in front of it, else the value will be printed as it is. For example, if we use "%5s" then at least 5 places will be allocated. The width is used to specify the minimum number of spaces in the console for the output. For example, hyphen(-) can be used to left-justify our string and comma(,) can be used to add thousands-separator. public static void main(String args)įlags are used to modify the formatted output in different ways. The following code example demonstrates the use of uppercase and lowercase conversion characters. Example: Formatting Lowercase and Uppercase in print() "c" will not convert uppercase to lowercase. Remember that this will not work the other way round i.e. The same rule can be applied for strings and boolean. For example, if we use "C" instead of "c", then the character value will be printed in uppercase. Some conversion characters can also be used to convert letters to uppercase. public static void main(String args)Įxception in thread "main" : d != Īt java.base/$FormatSpecifier.failConversion(Formatter.java:4426)Īt java.base/$FormatSpecifier.printInteger(Formatter.java:2938)Īt java.base/$FormatSpecifier.print(Formatter.java:2892)Īt java.base/(Formatter.java:2673)Īt java.base/java.io.PrintStream.format(PrintStream.java:1209)Īt java.base/java.io.PrintStream.printf(PrintStream.java:1105) Consider the example shown below where the conversion character for integers is used to format a string. If they do not match then we will get an IllegalFormatConversionException. We must use the correct conversion character according to the data type of the variable or value. Printing an exponential floating-point number 1.000000e+01 Printing a floating-point number 10.000000 ("Printing an exponential floating-point number %e %n", 10.0) ("Printing a floating-point number %f %n", 10.0)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |