Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class NumberToWordConverter {
private val specialNames = arrayOf("", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion")
private val tensNames = arrayOf("", " ten", " twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety")
private val numNames = arrayOf("", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen")
private fun convertLessThanOneThousand(number: Int): String {
var number = number
var current: String
if (number % 100 < 20) {
current = numNames[number % 100]
number /= 100
} else {
current = numNames[number % 10]
number /= 10
current = tensNames[number % 10] + current
number /= 10
}
if (number == 0) return current
return numNames[number] + " hundred" + current
}
fun convert(number: Int): String {
var number = number
if (number == 0) {
return "zero"
}
var prefix = ""
if (number < 0) {
number = -number
prefix = "minus"
}
var current = ""
var place = 0
do {
val n = number % 1000
if (n != 0) {
val s = convertLessThanOneThousand(n)
current = s + specialNames[place] + current
}
place++
number /= 1000
} while (number > 0)
return (prefix + current).trim { it <= ' ' }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.