Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format in Kotlin string templates

People also ask

What is format in Kotlin?

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.

What does ?: Mean in Kotlin?

AndroidMobile DevelopmentApps/ApplicationsKotlin. In Kotlin, "!!" is an operator that is known as the double-bang operator. This operator is also known as "not-null assertion operator". This operator is used to convert any value to a non-NULL type value and it throws an exception if the corresponding value is NULL.

What is string template Kotlin?

String templates are String literals that contain embedded expressions. For example, this code in Java: String message = "n = " + n; In Kotlin is just: val message = "n = $n" Any valid Kotlin expression may be used in a String template: val message = "n + 1 = ${n + 1}"

What is Kotlin string interpolation?

String interpolation in Kotlin allows us to easily concatenate constant strings and variables to build another string elegantly.


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.


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)

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

It's simple, use:

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

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