Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created January 15, 2014 10:19
Show Gist options
  • Save davepkennedy/8433906 to your computer and use it in GitHub Desktop.
Save davepkennedy/8433906 to your computer and use it in GitHub Desktop.
Number to text (not quite perfect)
object numbertext {
val singleDigits = Array("zero", "one","two","three","four","five","six","seven","eight","nine")
//> singleDigits : Array[String] = Array(zero, one, two, three, four, five, six
//| , seven, eight, nine)
val teens = Array("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen")
//> teens : Array[String] = Array(ten, eleven, twelve, thirteen, fourteen, fift
//| een, sixteen, seventeen, eighteen, nineteen)
val tens = Array ("","","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety")
//> tens : Array[String] = Array("", "", twenty, thirty, fourty, fifty, sixty,
//| seventy, eighty, ninety)
def numberText(number: Int): String = {
def toDigit (c: Char, a: Array[String]): String = a(c - '0')
def helper (ns: String): String = ns.length match {
case l if l > 3 =>
val (high, low) = ns.splitAt (l - 3)
helper(high) + " thousand " + helper(low)
case l if l == 3 =>
val (high, low) = ns.splitAt(l - 2)
helper(high) + " hundred " + helper(low)
case l if l == 2 => if (ns(0) == '1') {
toDigit(ns(1), teens)
} else {
toDigit(ns(0), tens) + " " + toDigit(ns(1), singleDigits)
}
case l if l == 1 => toDigit(ns(0), singleDigits)
case l if l == 0 => ""
}
helper(number.toString)
} //> numberText: (number: Int)String
numberText(1462) //> res0: String = one thousand four hundred sixty two
}
@davepkennedy
Copy link
Author

To be perfect I'd like one thousand four hundred AND sixty two

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