Skip to content

Instantly share code, notes, and snippets.

@azakordonets
Created May 31, 2017 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azakordonets/42b036787c44b3c85c7872be131c96a1 to your computer and use it in GitHub Desktop.
Save azakordonets/42b036787c44b3c85c7872be131c96a1 to your computer and use it in GitHub Desktop.
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