Format in kotlin string templates

前端 未结 6 1327
青春惊慌失措
青春惊慌失措 2020-12-12 17:40

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

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

But

6条回答
  •  青春惊慌失措
    2020-12-12 18:11

    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
    

提交回复
热议问题