【问题标题】:Dependency to format values to human readable form in Kotlin在 Kotlin 中将值格式化为人类可读形式的依赖性
【发布时间】:2021-01-06 00:03:15
【问题描述】:
我正在 android studio 的 Kotlin 中创建一个应用程序。我想在我的应用程序中显示值,这样如果数字很长,比如说以百万或十亿为单位,它会截断它并使用后缀显示它,例如 K(tousand) M(million), 等等。
例如:如果值为331330464,它将显示为331.3 M。
是否存在允许我进行这种格式化的依赖项?
【问题讨论】:
标签:
android
android-studio
kotlin
number-formatting
【解决方案1】:
我为Long 类开发了一个扩展函数,它提供了人类可读的价值:
HumanReadableExt.kt
import kotlin.math.log10
import kotlin.math.pow
val Long.formatHumanReadable: String
get() = log10(toDouble()).toInt().div(3).let {
val precision = when (it) {
0 -> 0; else -> 1
}
val suffix = arrayOf("", "K", "M", "G", "T", "P", "E", "Z", "Y")
String.format("%.${precision}f ${suffix[it]}", toDouble() / 10.0.pow(it * 3))
}
所以,println(331330464L.formatHumanReadable) 打印:
331.3 百万
对于小于 1000 的值,它会返回确切的数字:
println(331L.formatHumanReadable) 打印:
331