Skip to content

Instantly share code, notes, and snippets.

@m4kvn
Created July 16, 2021 19:44
Show Gist options
  • Save m4kvn/4d8482b01401c150a24cc9f75cf90931 to your computer and use it in GitHub Desktop.
Save m4kvn/4d8482b01401c150a24cc9f75cf90931 to your computer and use it in GitHub Desktop.
fun Long.toUnits(units: Array<String>): String {
var num = this
var rem = 0L
var index = -1
while ("$num".length > 4 && index < units.lastIndex) {
rem = num % 10000
num /= 10000
index += 1
}
val unit = if (index > -1) units[index] else ""
val numString = if ("$num".length == 1)
"${num}.${rem / 1000}" else
"%,d".format(num)
return numString + unit
}
fun main() {
val units = arrayOf("万", "億")
println(7777L.toUnits(units)) // 7,777
println(770000L.toUnits(units)) // 77万
println(77000L.toUnits(units)) // 7.7万
println(77770000L.toUnits(units)) // 7,777万
println(770000000L.toUnits(units)) // 7.7億
println(7777770000000L.toUnits(units)) // 77,777億
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment