Format in kotlin string templates

MajesticRa picture MajesticRa · Apr 15, 2014 · Viewed 145k times · Source

Kotlin has an excellent feature called string templates. I really love it.

 val i = 10 
 val s = "i = $i" // evaluates to "i = 10"

But is it possible to have any formatting in the templates? For example, I would like to format Double in string templates in kotlin, at least to set a number of digits after a decimal separator:

val pi = 3.14159265358979323
val s = "pi = $pi??" // How to make it "pi = 3.14"?

Answer

Andrey Breslav picture Andrey Breslav · Apr 15, 2014

Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:

"pi = ${pi.format(2)}"

the .format(n) function you'd need to define yourself as

fun Double.format(digits: Int) = "%.${digits}f".format(this)

There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.