Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NumberToWords converts an Int into English words
// NumberToWords converts an Int into English words
object NumberToWords extends App{
val num2Word=Map((0, "Zero"), (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"),
(20, "Twenty"), (30, "Thirty"),
(40, "Forty"), (50, "Fifty"),
(60, "Sixty"), (70, "Seventy"),
(80, "Eighty"), (90, "Ninety"),
(100, "Hundred"), (1000, "Thousand"),
(1000000, "Million"), (1000000000, "Billion")
)
def bigNums(x: Int, limits: List[Int], stringBuilder: StringBuilder): Int={
var i=x
for {
limit <- limits
} {
val units=i/limit
if (units > 0 && units<1000){
stringBuilder++=toWords(units)+" "+num2Word(limit)+" "
i-=units*limit
if (limit == 100 && i!=0) stringBuilder++="and "
}
}
i
}
def toWords(i: Int): String= {
var x=i
val out=new StringBuilder("")
x=bigNums(x,List(1000000000,1000000,1000,100),out)
if (x<100 && x>=20){
val tens=x/10*10
out++=num2Word(tens)+" "
x-=tens
}
if (x<20) {
if (x>0 || i==0)
out++=num2Word(x)
}
out.toString()
}
println(toWords(0))
println(toWords(1))
println(toWords(20))
println(toWords(70))
println(toWords(71))
println(toWords(111))
println(toWords(8421))
println(toWords(676123))
println(toWords(923676123))
println(toWords(1923676123))
println(toWords(Int.MaxValue))
}
Zero
One
Twenty
Seventy
Seventy One
One Hundred and Eleven
Eight Thousand Four Hundred and Twenty One
Six Hundred and Seventy Six Thousand One Hundred and Twenty Three
Nine Hundred and Twenty Three Million Six Hundred and Seventy Six Thousand One Hundred and Twenty Three
One Billion Nine Hundred and Twenty Three Million Six Hundred and Seventy Six Thousand One Hundred and Twenty Three
Two Billion One Hundred and Forty Seven Million Four Hundred and Eighty Three Thousand Six Hundred and Forty Seven
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment