Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 134 ยท Getting Started

String Templates and Formatting

Learn Kotlin string templates and formatting - $name, ${expression}, escaping the dollar sign, format() and %-specifiers, padStart, padEnd, number rounding, buildString and aligned tables.

Programs constantly turn values into text: "Hello, Ada", "3 items for $12.50", a table of results. Gluing pieces together with + works but gets ugly fast, and numbers need extra care (how many decimals? aligned in columns?). Kotlin gives you two main tools: string templates, which insert values directly into a literal, and formatting functions, which control width, padding and decimals.

This lesson shows both, then builds up to a small aligned report. If you have not yet seen how strings are created and compared, read Strings first.

String templates

Put a $ in front of a variable name inside a string and Kotlin replaces it with that variable's value. To insert any expression, wrap it in ${ ... }:

Kotlin Templates with $name and ${expression}

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The short form $name takes only a simple identifier. As soon as you need a property access, a function call, arithmetic or an if, use the braces. A very common beginner slip is writing "$items.size": Kotlin sees $items followed by the plain text .size. The next example shows it and the fix.

Kotlin The classic template mistake

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line prints Wrong: [a, b, c].size, because $items became the list text and .size stayed literal. The second prints the number 3.

A literal dollar sign

If a $ is followed by something that could be a name or a {, it starts a template. To print a real dollar sign, escape it with a backslash, or put it before a character that cannot start a name. In raw strings (triple quotes) where backslashes do not work, use ${'$'}:

Kotlin Printing a dollar sign

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Kotlin 2.x also has multi-dollar interpolation (for example $$"..." strings) for text that contains many dollar signs, such as JSON Schema. It is a niche feature; the escapes above cover nearly every real program.

Why templates beat concatenation

Compare the same message built three ways. Templates are shorter, show the shape of the output, and convert non-strings automatically. With +, a number on the left side does not even compile:

Kotlin Template versus plus (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports an error like none of the following candidates is applicable for Int.plus, because Int has plus overloads only for numbers. Write "$count items" and the problem disappears.

format(): width, decimals and padding

Templates insert values as toString() makes them, so 1.0 / 3 prints 0.3333333333333333. For control, use String.format or the extension "...".format(...), which share the syntax of C's printf (the same as Java's Formatter). Each % specifier consumes one argument:

Specifier Meaning Example result
%d integer 42
%5d integer in width 5, right aligned 42
%05d zero padded to width 5 00042
%.2f floating point with 2 decimals 3.14
%8.3f width 8, 3 decimals 3.142
%s any value as text Kotlin
%-8s text, left aligned in width 8 Kotlin
%x hexadecimal ff
%,d thousands separators 1,234,567
%b Boolean true
%% a literal percent sign %
Kotlin Formatting numbers with format()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two things deserve attention. First, %d needs an integer type; passing a Double throws IllegalFormatConversionException at run time, because format strings are not checked by the compiler. Second, locale: %f and %,d use the default locale of the machine, so the decimal separator can be a comma on a German computer. Pass Locale.US (or another explicit locale) when the text must be identical everywhere, for example in files or tests.

Kotlin A mismatched specifier (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The error is java.util.IllegalFormatConversionException: d != java.lang.Double. Use %.2f for a Double, or convert first with toInt() if you really want a whole number. Remember that the exception comes at run time, so code paths with unusual formats need a test.

Rounding

%.2f rounds half up using the decimal expansion of the floating-point value. Double cannot store most decimals exactly, so borderline cases can surprise you: "%.2f".format(2.675) prints 2.68 in some languages and 2.67 in others depending on the stored binary value. For money, use integers (cents) or BigDecimal and see Working with Numbers. To round a number itself rather than its text, use kotlin.math.round or roundToInt().

padStart, padEnd and building tables

Sometimes you do not need the full power of format. padStart(width, char) pads on the left (right-aligns), and padEnd pads on the right (left-aligns). Combined with templates they make clean columns:

Kotlin An aligned report with padStart and padEnd

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both styles produce identical columns. padStart and padEnd work on any string and are easy to read; format packs the whole layout into one line. Neither shortens a value that is already longer than the width, so a very long name pushes the columns out of line. Cut it first with take(14) if that matters.

buildString and multi-line output

When a message is assembled from many parts, conditionals and loops, template concatenation becomes awkward. buildString gives you a StringBuilder as this, so you can append piece by piece. Since Kotlin 1.4, appendLine replaced the removed appendln:

Kotlin buildString with appendLine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that buildString returns a normal String. You can print it, store it, or compare it later, and the builder itself is thrown away. Using a Map that keeps insertion order (linkedMapOf) keeps the printed order predictable; see Maps.

Practical advice

  • Use templates for ordinary messages: "$name scored $score".
  • Use ${...} whenever the expression is more than a bare name, and never nest quotes carelessly: "${map["key"]}" works in Kotlin, but if it looks cramped, compute a val first.
  • Use format (with an explicit Locale when the output must be stable) for decimals, widths and thousands separators.
  • Do not format money with Double arithmetic. Keep integers of cents and format at the end.
  • A template calls toString() on the value. Your own classes print as ClassName@1b2c3d unless you override it or use a data class (see Data Classes).
  • Avoid heavy logic inside templates; a long expression in ${...} is a sign that you need a named helper function.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does println("Size: $list.size") print if list holds [1, 2]?

    The short form $list only takes the identifier, so the list text is inserted and .size remains plain text. Use ${list.size}.
  2. 2. How do you print a literal dollar sign before a number stored in price?

    \$ is an escaped dollar sign, and the following $price is a normal template.
  3. 3. What does "%05d".format(42) return?

    %05d pads an integer with zeros on the left to a total width of 5.
  4. 4. Why can "%d".format(9.99) fail?

    The specifier is not verified by the compiler. A Double with %d throws IllegalFormatConversionException.
  5. 5. Which call makes the number format identical on every computer?

    %f and %,d follow the default locale unless you pass one explicitly, such as Locale.US.

Summary

  • $name inserts a variable; ${expression} inserts any expression; \$ prints a dollar sign.
  • Templates call toString(), so they never need manual conversion, unlike + with an Int on the left.
  • "%.2f".format(x) and String.format(Locale.US, ...) control decimals, width, padding and separators; mismatched specifiers fail at run time.
  • padStart and padEnd right- and left-align text for simple tables.
  • buildString with append and appendLine assembles longer text efficiently.

Next: Reading Input