Use a string template: "Hello, $name" puts a variable into the text and "Total: ${price * qty}" an expression. For decimals and widths, call format on a pattern: "%.2f".format(Locale.US, x) turns 3.14159 into 3.14. padStart(3, '0') adds leading zeros, list.joinToString(", ") joins a list, and a literal dollar sign is written "\$", or ${'$'} inside a """ raw string.
In Kotlin you rarely need String.format or + to build text: a string template writes the value straight into the string literal. Formatting with a pattern is still there for decimals, widths and thousands separators, as an extension function on the pattern. The sections below cover templates, format with its specifiers and locales, padStart and padEnd for aligned columns, joining text with +, buildString and joinToString, multi-line raw strings, and the dollar sign that templates make special, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1String templates: $name and ${expression}Recommended
Inside a string literal, $ followed by a name inserts that value, and ${…} inserts the result of any expression: arithmetic, a property, a function call, an if or an Elvis operator. The value is converted with toString(), so lists, data classes and numbers need nothing extra. This replaces the Java habit "Hello, " + name + "!" and most uses of String.format("%s", …). Use braces whenever the template is more than a plain name: a bare $ only reads letters, digits and underscores, so $user.name stops at user.
data class User(val name: String, val age: Int) fun main() { val name = "Ann" val user = User("Bo", 31) val items = listOf("pen", "ink") // $name for a variable, ${...} for any expression println("Hello, $name!") println("$name has ${name.length} letters") println("Next year ${user.name} turns ${user.age + 1}") // A property needs braces: $user.name stops after user println("Wrong: $user.name") println("Right: ${user.name}") // Braces also end the name when letters follow println("Two ${name}s") // Calls, if, collections and nulls all work println("Items: $items, first ${items.first()}") println("Status: ${if (user.age >= 18) "adult" else "minor"}") val nick: String? = null println("Nick: $nick") println("Nick: ${nick ?: "none"}") }
Output
The Wrong line is the classic mistake: $user.name inserts the whole object, User(name=Bo, age=31), and then the text .name. With braces you get Bo. In the same way "${name}s" gives Two Anns, where $names would look for a variable called names. A list prints as [pen, ink], and quotes inside ${…} need no escaping. A nullable value that is null prints as the text null, so give it a fallback with ?: when the string is shown to people.
2Decimals and widths: "%.2f".format()
A template prints a Double with all its digits. To control decimals, width, padding or grouping, Kotlin keeps Java's format specifiers and adds an extension: "%.2f".format(x) is the same as String.format("%.2f", x), and both return a String. Without a Locale they use the machine's default, so on a German machine %.2f writes 3,14; pass Locale.US (or the user's locale) as the first argument when the result must be predictable. The common specifiers: %s any value, %d whole numbers, %f decimals, %x hex, %% a percent sign, with a width, - for left-aligned, 0 for zero padding, + for a sign and , for grouping.
import java.util.IllegalFormatException import java.util.Locale fun main() { val price = 3.14159 // Two decimals in the machine's default locale println("%.2f".format(price)) println(String.format("%.2f", price)) // Pass a locale when the output must not depend on the machine val big = 1234567.891 println("%,.2f".format(Locale.US, big)) println("%,.2f".format(Locale.GERMANY, big)) // Several values; %% is a literal percent sign println("%d items at %s: %.1f%%".format(Locale.US, 3, "noon", 99.456)) // Width, left-align, zero padding, sign, other bases println("[%5d] [%-5d] [%05d] [%+d]".format(42, 42, 42, 42)) println("%x %X %o %.3e".format(Locale.US, 255, 255, 8, 12345.678)) // %1$s reuses argument 1; in Kotlin the $ needs a backslash println("%1\$s, %1\$s, %2\$d".format("echo", 2)) // Halves round up println("%.0f %.0f %.2f".format(Locale.US, 2.5, 3.5, 2.675)) // The type must match: %f wants a Double, not an Int try { println("%.2f".format(3)) } catch (e: IllegalFormatException) { println(e.message) } println("%.2f".format(Locale.US, 3.toDouble())) }
Output
The first two lines print 3.14 here because this page runs with an en_US default; your machine may differ. With explicit locales, the same number is 1,234,567.89 in Locale.US and 1.234.567,89 in Locale.GERMANY. %5d right-aligns in five characters, %-5d left-aligns and %05d pads with zeros. %1$s picks the first argument by position, written "%1\$s" because a bare $s would be a template. Rounding is half up (2.5 gives 3, 2.675 gives 2.68). A type mismatch is a runtime error, not a compile error: "%.2f".format(3) throws IllegalFormatConversionException with f != java.lang.Integer, so convert with toDouble() first. Too few arguments throws MissingFormatArgumentException.
3Leading zeros and columns: padStart and padEnd
padStart(length, char) adds characters on the left until the string is length long, and padEnd adds them on the right; the fill defaults to a space, and a string that is already long enough comes back unchanged (never cut). They work on strings only, so call toString() on a number first. That makes them handy for leading zeros and for lining up text in columns. A format string does the same with widths (%-10s, %5d) and can round the numbers in the same step.
import java.util.Locale data class Item(val name: String, val qty: Int, val price: Double) fun main() { // Fill to a width; the default fill is a space println("7".padStart(3, '0')) println("[" + "x".padStart(5) + "]") println("[" + "x".padEnd(5, '.') + "]") println("toolong".padStart(3)) // padStart does not know about signs; %03d does println("-5".padStart(3, '0')) println("%03d".format(-5)) val items = listOf( Item("Pencil", 12, 0.5), Item("Notebook", 3, 4.25), Item("Backpack", 1, 39.9), ) // A table with padEnd for text and padStart for numbers println("Name".padEnd(10) + "Qty".padStart(5) + "Price".padStart(9)) for (item in items) { val qty = item.qty.toString() val price = "%.2f".format(Locale.US, item.price) println(item.name.padEnd(10) + qty.padStart(5) + price.padStart(9)) } println("-".repeat(24)) // The same rows with the widths in one format string for ((name, qty, price) in items) { println("%-10s%5d%9.2f".format(Locale.US, name, qty, price)) } val total = items.sumOf { it.qty * it.price } println("%-10s%14.2f".format(Locale.US, "Total", total)) }
Output
"7".padStart(3, '0') gives 007, and toolong stays as it is because it is longer than 3. The sign trap: "-5".padStart(3, '0') gives 0-5, while %03d gives -05, so use the format string for numbers that can be negative. Both tables come out identical; the format string version is shorter and writes 39.9 as 39.90 on the way. The columns only line up in a monospaced font, such as a console or a log file.
4Joining strings: +, buildString and joinToString
+ works as in Java, and += on a var appends. A template usually reads better, and it avoids two traps: + runs left to right, so a number added after a string becomes text, and a String must come first, since 1 + " apples" doesn't compile (an Int has no plus that takes a String). When you build text piece by piece in a loop, use buildString, which gives you a StringBuilder and returns the finished String. For a collection, joinToString adds the separators for you.
fun main() { val first = "Ada" val last = "Lovelace" val n = 3 // + and += work as in Java println(first + " " + last) var label = "Step" label += " " + n println(label) // Left to right: "" + 3 + 1 is "31", not "4" println("" + n + 1) println("Sum: ${n + 1}") // A null String joins as the text "null" val nick: String? = null println("Nick: " + nick) println(nick + "!") // Many pieces in a loop: buildString wraps a StringBuilder val csv = buildString { append("id,name\n") for (i in 1..3) { append(i).append(",user").append(i).append('\n') } } print(csv) // A collection: joinToString with separator, prefix, transform val words = listOf("red", "green", "blue") println(words.joinToString()) println(words.joinToString(" | ")) println(words.joinToString(", ", "[", "]") { it.uppercase() }) println(words.joinToString(limit = 2)) }
Output
"" + n + 1 prints 31 because the first + already made a string; the template "${n + 1}" does the math first and prints 4. + accepts a nullable string on either side and writes null, hence null!. joinToString() uses ", " by default, takes a prefix, a postfix and a transform, and limit = 2 ends with .... Java's String.join("-", words) doesn't compile here (Unresolved reference 'join'.), because String means kotlin.String. One more trap: a line that starts with + is a new statement, so keep the + at the end of the line when you wrap a long expression, or you get Unresolved reference 'unaryPlus' for operator '+' on receiver of type 'String'.
5Multi-line raw strings: trimIndent and trimMargin
A raw string sits between triple quotes, """…""". It can span lines and has no backslash escapes, so Windows paths, quotes and regular expressions read exactly as written; templates still work. The lines keep the indentation of your source code, so finish the string with trimIndent(), which removes the indent all lines share plus the empty first and last line, or with trimMargin(), which removes everything up to a | at the start of each line and keeps any indentation after it.
fun main() { val name = "Ann" // No escapes inside """: backslashes and quotes are plain text println("""C:\new\table, "quoted", $name""") println("C:\\new\\table") println("""a\nb""") // Regex patterns read as written val digits = Regex("""\d+""") println(digits.findAll("a1 b22 c333").map { it.value }.toList()) // trimIndent drops the shared indent and the empty end lines val letter = """ Dear $name, Thanks for your order. Bye """.trimIndent() println(letter) // trimMargin cuts each line up to and including | val menu = """ |1. Start | 1a. Quick start |2. Quit """.trimMargin() println(menu) // Without trimming, the source indentation stays val loose = """ x """ println(loose.lines()) }
Output
The raw path and the escaped "C:\\new\\table" print the same C:\new\table, and """a\nb""" prints the two characters \n, not a line break. The regex finds [1, 22, 333] without doubled backslashes. trimIndent() keeps the extra two spaces before Thanks, and trimMargin() keeps the two after the |. The last line shows the untrimmed string: an empty first line, x with eight spaces in front, and the four spaces before the closing quotes. Pass another marker if your text contains |: trimMargin("#").
6A literal dollar sign in a string
Because $ starts a template, a dollar sign followed by a name or a brace needs escaping. In a normal string, write \$. A raw string has no backslash escapes, so the old trick there is ${'$'}: a template whose expression is the character $. Since Kotlin 2.2, multi-dollar interpolation is cleaner: put $$ before the opening quotes and only $$name is a template, while a single $ is plain text. That suits JSON schemas, shell scripts and prices. A $ that is not followed by a letter or a brace never needs escaping.
fun main() { val price = 5 val title = "Order" // Before a name, escape the $ with a backslash println("Cost: \$$price") // A $ that cannot start a template is plain text println("Cost: 5$ or $ 5") // Raw strings have no escapes: \$ stays a backslash println("""Not this: \$price""") println("""Cost: ${'$'}$price""") // Kotlin 2.2+: after $$", only $$ starts a template val schema = $$"""{"$schema": "v1", "title": "$$title"}""" println(schema) println($$"Cost: $$$price, not $price") }
Output
"\$$price" prints Cost: $5: the escaped dollar, then the template. In a raw string the backslash is kept, so """\$price""" prints Not this: \5, and ${'$'} is the way that works in every Kotlin version. In the $$ string, $schema stays as written and $$title becomes Order; in $$$price the first $ is text and the rest is the template, so it prints $5. If your project is older than Kotlin 2.2, use ${'$'} instead.
7Which should you use?
| Method | Number formatting | Best for |
|---|---|---|
| "Hi, $name: ${x + 1}" | None, uses toString() | Most text: values inside a sentence |
| "%.2f".format(Locale.US, x) | Decimals, width, grouping | Prices, percentages, hex, fixed widths |
| s.padStart(5, '0') | Width and fill only | Leading zeros, text columns |
| buildString { append(…) } | None | Text built in a loop |
| list.joinToString(", ") | Per item, with a transform | Lists with separators |
| """…""".trimIndent() | None | Multi-line text, paths, regex |
| $$"""…$$name…""" | None | Text full of $ signs (Kotlin 2.2+) |
| a + " " + b | None | Avoid for long text: a template reads better |
Frequently asked questions
How do I format a Double to two decimal places in Kotlin?
Use "%.2f".format(Locale.US, x), which returns a String: 3.14159 becomes "3.14" and 3.0 becomes "3.00". It rounds half up, so 2.675 gives "2.68". Without the Locale argument it uses the machine's locale, which writes "3,14" in Germany. If you need the rounded number rather than text, round the Double itself, for example with roundToInt() on a scaled value or with BigDecimal.
Does Kotlin have printf?
Not as its own function, but println("%d apples".format(5)) does the same, and Java's System.out.printf("%d apples, %.1f kg%n", 5, 2.25) works too: it prints "5 apples, 2.3 kg". Use %n or \n for the line break, since printf does not add one. In most code a string template, println("$count apples"), is simpler.
How do I add leading zeros to a number?
Either n.toString().padStart(3, '0') or "%03d".format(n); both turn 5 into "005". They differ for negative numbers: "-5".padStart(3, '0') gives "0-5", while "%03d".format(-5) gives "-05", so use the format string when the number can be negative.
How do I format money or thousands separators?
For grouping, add a comma flag: "%,.2f".format(Locale.US, 1234.5) gives "1,234.50". For a currency symbol, use NumberFormat.getCurrencyInstance(Locale.US).format(1234.5) from java.text, which gives "$1,234.50". Pick the locale on purpose: the symbol, the separators and their order all change with it.
How do I print a number without trailing zeros?
A template already drops them where it can: "${1.50}" prints 1.5, but a whole Double keeps one zero, 2.0. For "at most two decimals", use DecimalFormat("0.##") from java.text: it formats 1.5 as "1.5", 2.0 as "2" and 2.456 as "2.46". DecimalFormat follows the default locale too, so pass DecimalFormatSymbols(Locale.US) when that matters.
Is + slow? Should I use StringBuilder in Kotlin?
For one expression, no: a template or a single chain of + builds the result in one go, so a StringBuilder gains nothing and reads worse. It matters in loops: s += piece creates a new String on every pass. Build such text with buildString { append(piece) }, or with joinToString when you are joining a collection.
How do I format a date as a string?
Use java.time: LocalDate.of(2026, 12, 2).format(DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.US)) gives "02 Dec 2026". A template on the date, "$date", uses the ISO form "2026-12-02". Format strings also have date conversions such as %tY, but DateTimeFormatter patterns are easier to read.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground