Format in Kotlin string templates

String FormattingKotlin

String Formatting Problem Overview


Kotlin has an excellent feature called string templates.

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"?

String Formatting Solutions


Solution 1 - String Formatting

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)

This will work only in Kotlin/JVM.

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

Solution 2 - String Formatting

As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format())

See Kotlin's documentation

Your code would be:

val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)

Solution 3 - String Formatting

Kotlin's String class has a format function now, which internally uses Java's String.format method:

/**
 * Uses this string as a format string and returns a string obtained by substituting the specified arguments,
 * using the default locale.
 */
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)

Usage

val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14

Solution 4 - String Formatting

It's simple, use:

val str: String = "%.2f".format(3.14159)

Solution 5 - String Formatting

Since String.format is only an extension function (see here) which internally calls java.lang.String.format you could write your own extension function using Java's DecimalFormat if you need more flexibility:

fun Double.format(fracDigits: Int): String {
    val df = DecimalFormat()
    df.setMaximumFractionDigits(fracDigits)
    return df.format(this)
}

println(3.14159.format(2)) // 3.14

Solution 6 - String Formatting

A couple of examples:

infix fun Double.f(fmt: String) = "%$fmt".format(this)
infix fun Double.f(fmt: Float) = "%${if (fmt < 1) fmt + 1 else fmt}f".format(this)

val pi = 3.14159265358979323

println("""pi = ${pi f ".2f"}""")
println("pi = ${pi f .2f}")

Solution 7 - String Formatting

It has string formatting Example in Kotlin for Android TextView:

val format = String.format("<font color=#3177a3> test1: <b>%s</b><br> test2: <b>%s</b><br> test3: <b>%s</b></font>", "value1", "value2", "value3")
textView.text = format

Solution 8 - String Formatting

It has string formatting Example:

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMajesticRaView Question on Stackoverflow
Solution 1 - String FormattingAndrey BreslavView Answer on Stackoverflow
Solution 2 - String FormattingakhyView Answer on Stackoverflow
Solution 3 - String Formattinguser1767754View Answer on Stackoverflow
Solution 4 - String FormattingmasoomyfView Answer on Stackoverflow
Solution 5 - String FormattingWilli MentzelView Answer on Stackoverflow
Solution 6 - String FormattingLessneekView Answer on Stackoverflow
Solution 7 - String FormattingDeniz BabatView Answer on Stackoverflow
Solution 8 - String FormattingSibylView Answer on Stackoverflow