Search code examples
stringkotlinstring-interpolation

String interpolation for double number in Kotlin


How to use string interpolation for a double with 2 numbers after the period in Kotlin?

For example

val d = 3.54213
println("d = $d")

will get d = 3.54213.

I want to get d = 3.54.

Thank you.


Solution

  • You can try something like this :

       // string interpolation
        val d = 3.54213
        println("d = %.2f".format(d))
    

    This link too has the same answer but it says

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

    Soon, you would see this on Kotlin.

    Hope this helps!