Menu

Java String.format() Cheat Sheet: %s, %d, %.2f, Flags and Locale
📰

Java String.format() Cheat Sheet: %s, %d, %.2f, Flags and Locale

DEV Community: beginners·Tatyana Milkina·about 12 hours ago
#p2za7Zhr
#devtobeginners#devto#dev#format#string
Reading 0:00
15s threshold

On a laptop with German regional settings, String.format("%.2f", 0.5) returns "0,50" instead of "0.50" — and the very next Double.parseDouble(...) fails with NumberFormatException: For input string: "0,50" . Surprises like this disappear once you understand how string formatting in Java actually works.

String formatting in Java means building a string from a template in which format specifiers ( %d , %s , %.2f and others) are replaced with argument values. Formatted output is produced by String.format() , String.formatted() (Java 15+), System.out.printf() and the java.util.Formatter class, which powers all of them. You can format numbers, strings, characters, dates and times.

String.format(), printf() and formatted(): which one to use

If you need the result as a string, use String.format() or "template".formatted() ; if you want to print it right away, use System.out.printf() ; if the text is assembled in several steps or written to a file, use the Formatter class.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.