Use CompactDecimalFormat to format counts.

This commit is contained in:
Isira Seneviratne 2023-03-25 19:00:41 +05:30
parent d6232dfcda
commit 26735d2f88

View File

@ -1,14 +1,22 @@
package com.github.libretube.extensions
import android.icu.text.CompactDecimalFormat
import android.os.Build
import java.util.*
import kotlin.math.pow
fun Long?.formatShort(): String {
this ?: return (0).toString()
val value = this ?: 0
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
CompactDecimalFormat
.getInstance(Locale.getDefault(), CompactDecimalFormat.CompactStyle.SHORT)
.format(value)
} else {
val units = arrayOf("", "K", "M", "B", "T")
for (i in units.size downTo 1) {
val step = 1000.0.pow(i.toDouble())
if (this > step) return String.format("%3.0f%s", this / step, units[i]).trim()
if (value > step) return String.format("%3.0f%s", value / step, units[i]).trim()
}
value.toString()
}
return this.toString()
}