1

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.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
thuanle
  • 330
  • 6
  • 15

2 Answers2

2

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!

harshavmb
  • 3,404
  • 3
  • 21
  • 55
0

you can try it like this

val df = DecimalFormat("#.00")
val d1 = 3.54213
df.format(d1)
ChanghuiN
  • 1
  • 1