M. *_*ani 5 android number-formatting kotlin android-studio
我正在 android studio 中用 Kotlin 创建一个应用程序。我想在我的应用程序中显示值,这样如果数字很长,比如说数百万或数十亿,它会截断它并用后缀显示它,例如K(thousand) M(million)等。
例如:如果值为331330464,则显示为331.3 M。
是否存在允许我进行此格式化的依赖项?
我为类开发了一个扩展函数Long,它提供了人类可读的值:
HumanReadableExt.kt
import kotlin.math.log10
import kotlin.math.pow
val Long.formatHumanReadable: String
get() = log10(coerceAtLeast(1).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))
}
Run Code Online (Sandbox Code Playgroud)
所以,println(331330464L.formatHumanReadable)打印:
331.3M
对于低于 1000 的值,它返回确切的数字:
println(331L.formatHumanReadable)印刷:
第331章
| 归档时间: |
|
| 查看次数: |
522 次 |
| 最近记录: |