Skip to content

Instantly share code, notes, and snippets.

@worthlesscog
Created April 29, 2012 11:59
Show Gist options
  • Save worthlesscog/2549895 to your computer and use it in GitHub Desktop.
Save worthlesscog/2549895 to your computer and use it in GitHub Desktop.
Converting numbers to English text
object NumberText1 {
val u = Map(
1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four", 5 -> "five",
6 -> "six", 7 -> "seven", 8 -> "eight", 9 -> "nine", 10 -> "ten",
11 -> "eleven", 12 -> "twelve", 13 -> "thirteen", 14 -> "fourteen", 15 -> "fifteen",
16 -> "sixteen", 17 -> "seventeen", 18 -> "eighteen", 19 -> "nineteen"
)
val t = Map(
2 -> "twenty", 3 -> "thirty", 4 -> "forty", 5 -> "fifty",
6 -> "sixty", 7 -> "seventy", 8 -> "eighty", 9 -> "ninety"
)
val someAnd = Some("and")
def conv(n: Int) = {
def conv(n: Int, units: String*): List[Option[String]] = {
if (n > 0) {
val mod = n % 1000
val div = mod / 100
val rem = mod % 100
val and = if (div > 0 && rem > 0) someAnd else None
val tens = if (rem < 20) List(u.get(rem)) else List(t.get(rem / 10), u.get(rem % 10))
val triplet = u.get(div).map(h ⇒ h + " hundred") :: and :: tens
val unit = if (mod > 0) Some(units.head) else None
conv(n / 1000, units.tail: _*) ::: (triplet :+ unit)
} else List(None)
}
if (n > 0) {
val div = conv((n / 1000) * 1000, "", "thousand", "million", "billion")
val and = List(if (n > 1000 && n % 1000 < 99 && n % 100 > 0) someAnd else None)
val mod = conv(n % 1000, "")
(div ::: and ::: mod).flatten.mkString(" ")
} else "zero"
}
def main(args: Array[String]): Unit = {
(1 to 100).map(conv).foreach(println)
println(conv(10101010))
println(conv(909090909))
println(conv(1314159265))
println(conv(324872004))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment