Editor

Number to English Words

#155 · Strings · Advanced · 140 XP · about 30 min

Cheques, invoices and voice assistants need numbers written out in words. Write to_words(n) that returns the English words for the whole number n, in lowercase, following these rules:

  • 0 to 19 have their own words: zero, one, two, ..., ten, eleven, twelve, ..., nineteen.
  • The tens are twenty, thirty, forty, fifty, sixty, seventy, eighty and ninety. A tens word and a ones word are joined with a hyphen: forty-two.
  • Hundreds are written as a digit word followed by "hundred", then the rest if it is not zero: three hundred five, seven hundred.
  • Larger numbers are read in groups of three digits, each followed by "thousand", "million" or "billion". A group that is all zeros is left out completely.
  • Words are separated by single spaces, and there is no "and" anywhere.

Examples

to_words(42)       # returns 'forty-two'
to_words(1005)     # returns 'one thousand five'
to_words(7000210)  # returns 'seven million two hundred ten'

7,000,210 splits into the groups 7, 000 and 210: "seven million", nothing for the empty thousands, then "two hundred ten".

Constraints

  • 0 <= n <= 999,999,999,999

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.