TExcelTAD
Home › Kotlin › Kotlin String Templates & Formatting

Kotlin String Templates and Formatting

Building text from values is one of the most common things programs do. Kotlin's string templates make it painless, and format, padding helpers and raw strings cover tables, receipts and reports.

Template basics

Syntax Inserts
$name the value of a variable
${expression} the result of any expression
\$ a literal dollar sign
kotlin · try it yourself
data class Item(val name: String, val price: Double, val qty: Int)

fun main() {
    val item = Item("Lamp", 24.5, 2)
    println("Item: ${item.name}")
    println("Line total: ${item.price * item.qty}")
    println("Status: ${if (item.qty > 1) "multiple" else "single"}")
    println("Uppercase: ${item.name.uppercase()}")
    println("Cost in USD: \${item.price}")
}
Item: Lamp
Line total: 49.0
Status: multiple
Uppercase: LAMP
Cost in USD: $24.5

$ followed by a valid identifier is a template. If the next character is part of the name you don't mean, use braces: "${count}th" instead of "$countth".

Number formatting with format

String.format uses % placeholders (the same as Java's String.format/C's printf):

Placeholder Meaning Example Result
%d integer "%d".format(42) 42
%5d width 5, right-aligned "%5d".format(42) 42
%05d zero-padded "%05d".format(42) 00042
%.2f 2 decimals "%.2f".format(3.14159) 3.14
%,d thousands separator "%,d".format(1234567) 1,234,567
%s string "%s!".format("hi") hi!
%-8s width 8, left-aligned `"%-8s ".format("ab")`
%x hexadecimal "%x".format(255) ff
kotlin · try it yourself
fun main() {
    val pi = Math.PI
    println("%.2f".format(pi))
    println("%8.3f|".format(pi))
    println("%05d".format(42))
    println("%,d people".format(8_100_000_000))
    println("%s scored %d%%".format("Ana", 97))
    println("#%06X".format(0x7F52FF))
}
3.14
   3.142|
00042
8,100,000,000 people
Ana scored 97%
#7F52FF

Note: %% prints a literal percent sign. The decimal separator of format follows the system locale; pass Locale.US as the first argument (String.format(Locale.US, …)) when you need a guaranteed ..

Padding helpers

padStart and padEnd pad a string to a minimum length — great for aligned columns without format strings:

kotlin · try it yourself
fun main() {
    val rows = listOf("Coffee" to 3.5, "Croissant" to 2.25, "Juice" to 4.0)
    println("ITEM".padEnd(12) + "PRICE".padStart(7))
    for ((name, price) in rows) {
        println(name.padEnd(12, '.') + "%.2f".format(price).padStart(7))
    }
    println("-".repeat(19))
    println("TOTAL".padEnd(12) + "%.2f".format(rows.sumOf { it.second }).padStart(7))
}
ITEM          PRICE
Coffee......   3.50
Croissant...   2.25
Juice.......   4.00
-------------------
TOTAL          9.75

Raw strings

Triple-quoted strings can span lines and treat backslashes literally — templates still work inside them. trimIndent() removes the common indentation; trimMargin() removes everything up to a | margin character.

kotlin · try it yourself
fun main() {
    val user = "kai"
    val count = 3
    val email = """
        Hi $user,
        you have $count new messages.
        Path: C:\Users\$user\inbox
    """.trimIndent()
    println(email)

    val poem = """
        |Roses are red,
        |  Kotlin is neat
    """.trimMargin()
    println(poem)
}
Hi kai,
you have 3 new messages.
Path: C:\Users\kai\inbox
Roses are red,
  Kotlin is neat

To put a literal $ in a raw string (where \$ doesn't work), write ${'

#39;}.

Building strings in loops

buildString gives you a StringBuilder and returns the result — efficient and readable:

kotlin · try it yourself
fun main() {
    val triangle = buildString {
        for (i in 1..4) {
            append(" ".repeat(4 - i))
            appendLine("*".repeat(2 * i - 1))
        }
    }
    print(triangle)
}
   *
  ***
 *****
*******

Tip: Prefer templates over + concatenation: "Hello, $name!" is shorter, faster to read and avoids accidental "1" + 2 surprises.

Test yourself

What does "%.1f".format(2.46) produce?

  1. 2.4
  2. 2.5
  3. 2.46
  4. 2

Which is correct to print the length of name inside a template?

  1. "$name.length"
  2. "${name.length}"
  3. "$(name.length)"
  4. "#{name.length}"

What does "7".padStart(3, '0') return?

  1. "700"
  2. "007"
  3. "7"
  4. "0007"