在 Kotlin 中将值格式化为人类可读形式的依赖性

Dependency to format values to human readable form in Kotlin

我正在 android 工作室用 Kotlin 创建一个应用程序。我想在我的应用程序中显示值,这样如果数字很长,比如数百万或数十亿,它会截断它并用后缀显示它,比如 K(thousand) M(million ), .

例如:如果值为331330464,则显示为331.3 M

是否有允许我执行此格式设置的依赖项?

我为 Long class 开发了一个扩展函数,它提供了它的 human-readable 值:

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 M

对于小于 1000 的值,它 returns 确切的数字:

println(331L.formatHumanReadable) 打印:

331