Created
July 16, 2021 19:44
-
-
Save m4kvn/4d8482b01401c150a24cc9f75cf90931 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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