Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created May 12, 2021 18:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/1ea2dc6452760d3cde70205d407b2bb2 to your computer and use it in GitHub Desktop.
Save fancellu/1ea2dc6452760d3cde70205d407b2bb2 to your computer and use it in GitHub Desktop.
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