Skip to content

Instantly share code, notes, and snippets.

@Skaldebane
Created August 18, 2022 00:48
Show Gist options
  • Save Skaldebane/d4b58ccb7d333a3346c36b886fc8e15e to your computer and use it in GitHub Desktop.
Save Skaldebane/d4b58ccb7d333a3346c36b886fc8e15e to your computer and use it in GitHub Desktop.
Small Kotlin helper function for converting a number to its textual representation, with a heavily functional approach.
fun main() {
while (true) {
val number = input("Number: ").toIntOrNull()
if (number != null)
println(number.getName())
else
println("Invalid Number!")
}
}
fun input(message: String): String {
print(message)
return readln()
}
val units = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val specialTens =
listOf("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen")
val tens = listOf("twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety")
val orders = listOf("thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion")
fun Int.getName(): String = when (this) {
in 0..9 -> units[this]
in 10..19 -> specialTens[this]
20, 30, 40, 50, 60, 70, 80, 90 -> tens[this[0] - 2]
in 21..99 -> "${tens[this[0] - 2]} ${units[this[1]]}"
in 100..999 -> buildString {
append("${units[this@getName[0]]} hundred")
if (this@getName % 100 != 0)
append(" ${this@getName[1..2].getName()}")
}
else -> buildString {
val length = this@getName.length
val order = (length - 1) / 3 // 1 for thousands, 2 for millions, etc...
append("${this@getName[0..length - (3 * order + 1)].getName()} ${orders[order - 1]}")
if (this@getName % orderDivider(order) != 0)
append(" ${this@getName[length - 3 * order until length].getName()}")
}
}
operator fun Int.get(index: Int) = "$this"[index].digitToInt()
operator fun Int.get(range: IntRange) = "$this".substring(range).toInt()
fun orderDivider(order: Int) = "1${"0".repeat(3 * order)}".toInt()
val Int.length
get() = "$this".length
@Skaldebane
Copy link
Author

Skaldebane commented Aug 18, 2022

For now this is limited by Int's constraints, but may be improved by using Long or BigInt instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment