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

推荐答案

遗憾的是,字符串模板中还没有内置的格式支持,作为一种解决办法,您可以使用如下内容:

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

Kotlin相关问答推荐

如何访问方法引用的接收者?

如何进行基于lambda/谓词的两个列表的交集?

为什么 Kotlin 中没有 init 块的注释

始终抛出的函数 - 具有块主体的函数中需要的返回表达式

可组合项在返回后返回时组合导航句柄

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

区分函数和扩展

Kotlin 中私有集的完整语法 struct 是什么?

是什么让 Kotlin 中的 String 类能够使用方括号?

Kotlin - 创建指定长度的随机整数的 ArrayList?

如何在 IntelliJ 中更改 Kotlin 的this property has a backing field代码编辑器突出显示?

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

如何在 android jetpack compose 中相互重叠列表项?

Kotlin惰性默认属性

如果我可以将 Flow 和 StateFlow 与生命周期范围 \ viewLifecycleOwner.lifecycleScope 一起使用,那么在 ViewModel 中使用 LiveData 有什么意义

用mockk验证属性设置程序吗?

Kotlin中的属性(properties)和参数(parameters)有什么区别?

Failure delivering result on activity result

Android Jetpack Compose 中的文本渐变

在Kotlin中创建通用二维数组