Dependency to format values to human readable form in Kotlin

Viewed 213

I am creating an app in Kotlin in android studio. I want to display values in my app so that if the number is long, let's say in millions or billions, it would truncate it and display it with a suffix, like K(thousand) M(million), etc.

For example: If the value was 331330464, it would display as 331.3 M.

Is there a dependency that allows me to do this formatting?

1 Answers

I've developed an extension function for Long class which delivers the human-readable value of it:

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))
    }

So, println(331330464L.formatHumanReadable) prints:

331.3 M

And for the values lower than 1000, it returns the exact number:

println(331L.formatHumanReadable) prints:

331

Related