Format in kotlin string templates

丶灬走出姿态 提交于 2019-11-28 17:07:28

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

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

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

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

akhy

As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format())

See Kotlin's documentation

Your code would be:

val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
user1767754

Kotlin's String class has a format function now, which internally uses Java's String.format method:

/**
 * Uses this string as a format string and returns a string obtained by substituting the specified arguments,
 * using the default locale.
 */
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)

Usage

val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14
masoomyf

Its simple, Use:

val str:String = "%.2f".format(3.14159)

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

Try take. It returns a list containing first n elements.

val pi = 3.14159265358979323
val s = pi.take(4)

But it's just about the collections as rekire said, who politely corrected me in the comment below.

You can convert to string, use take and convert back to Double.

val a = 3.14159265358979323
val b = a.toString().take(4).toDouble()

Not the best idea though but it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!