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

问题描述

我正在Android Studio中的Kotlin中创建一个应用程序。我想在我的应用程序中显示值,以便如果该数字很长(以百万或数十亿计),它将截断它并显示后缀,例如K(千)M(百万),

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

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

解决方法

我为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 M

对于小于1000的值,它将返回准确的数字:

println(331L.formatHumanReadable)打印:

331