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

标签 android android-studio kotlin number-formatting

我正在 android studio 的 Kotlin 中创建一个应用程序。我想在我的应用程序中显示值,这样如果数字很长,比如数百万或数十亿,它会截断它并用后缀显示它,如 K (千)M (百万)等
例如:如果值为 331330464 ,它将显示为 331.3 M .
是否存在允许我进行这种格式化的依赖项?

最佳答案

我为 Long 开发了一个扩展功能提供人类可读值(value)的类:
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

关于android - 在 Kotlin 中将值格式化为人类可读形式的依赖性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63966076/

相关文章:

java - 使用 FirebaseDatabase 检索数据

javascript - 如何获取选中的所有段落的id?

android - 以编程方式获取选定的行数据

android - 为什么activity_main.xml屏幕只是白色?

android - 在没有生命周期所有者的情况下使用 LiveData

android - 指定为非空的参数为空 - 在 Kotlin 中加载图像

android - 什么是图片监听器?

flutter - '类型 'Color' 不是 'MaterialColor' 的子类型,每次我在 Android Studio 的模拟器(Android 和 iOS)上构建我的 Flutter 应用程序时都会出现错误

android - 无法为任务 ':app:javaPreCompileProductionDebug' 捕获输入文件的指纹

kotlin - 警告 : API 'variant.getPackageLibrary()' is obsolete and has been replaced with 'variant.getPackageLibraryProvider()'