以Kotlin字符串模板格式 [英] Format in kotlin string templates

查看:489
本文介绍了以Kotlin字符串模板格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin具有一项出色的功能,称为字符串模板.我真的很喜欢它.

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

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

但是模板中可以有任何格式吗?例如,我想在kotlin中格式化字符串模板中的Double格式,至少在小数点分隔符后设置一些数字:

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

推荐答案

不幸的是,还没有内置的字符串模板格式支持,作为一种变通方法,您可以使用以下方法:

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)}"

您需要将自己定义为的.format(n)函数

the .format(n) function you'd need to define yourself as

fun Double.format(digits: Int) = "%.${digits}f".format(this)

Kotlin目前显然缺少这里的一项功能,我们将对其进行修复.

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

这篇关于以Kotlin字符串模板格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆