Skip to content

Instantly share code, notes, and snippets.

@rezemika
Created April 3, 2018 19:15
Show Gist options
  • Save rezemika/73fff23671a72b77dcf6919c3f903917 to your computer and use it in GitHub Desktop.
Save rezemika/73fff23671a72b77dcf6919c3f903917 to your computer and use it in GitHub Desktop.
Python - Number to words
"""
This script returns a string of a number in letters (**in french**) from a positive integer.
$ python3 number.py 1254
mille deux-cent cinquante-quatre
It works for numbers from 0 to 999 999 999 999 (1 trillion minus 1).
"""
import sys
SINGLE_NUMBERS = {
0: "zéro",
1: "un",
2: "deux",
3: "trois",
4: "quatre",
5: "cinq",
6: "six",
7: "sept",
8: "huit",
9: "neuf",
10: "dix",
11: "onze",
12: "douze",
13: "treize",
14: "quatorze",
15: "quinze",
16: "seize"
}
NUMBER_NAMES = {
"units": {
1: "et-un",
2: "deux",
3: "trois",
4: "quatre",
5: "cinq",
6: "six",
7: "sept",
8: "huit",
9: "neuf"
},
"tens": {
1: "dix",
2: "vingt",
3: "trente",
4: "quarante",
5: "cinquante",
6: "soixante",
7: "septente",
8: "octante",
9: "nonante"
}
}
def render_tens_units(tens, units):
if units == 0:
return NUMBER_NAMES["tens"][tens]
return NUMBER_NAMES["tens"][tens] + '-' + NUMBER_NAMES["units"][units]
def render(n):
if n < 0 or type(n) is not int:
raise ValueError("'n' must be a positive integer.")
if n < 17:
return SINGLE_NUMBERS.get(n)
if n < 100:
tens, units = divmod(n, 10)
return render_tens_units(tens, units)
if n < 1000:
hundreds, rest = divmod(n, 100)
tens, units = divmod(rest, 10)
if hundreds == 1:
h = "cent"
else:
h = SINGLE_NUMBERS.get(hundreds) + "-cent"
return h + ' ' + render_tens_units(tens, units)
if n < 10000:
thousands, rest = divmod(n, 1000)
if thousands == 1:
t = "mille"
else:
t = SINGLE_NUMBERS.get(thousands) + "-mille"
return t + ' ' + render(rest)
if n < 1000000:
thousands, rest = divmod(n, 1000)
return render(thousands) + "-mille " + render(rest)
if n < 1000000000:
millions, rest = divmod(n, 1000000)
if rest == 0:
return render(millions) + "-millions"
return render(millions) + "-millions " + render(rest)
if n < 1000000000000:
billions, rest = divmod(n, 1000000000)
if rest == 0:
return render(billions) + "-milliards"
return render(billions) + "-milliards " + render(rest)
return
if __name__ == '__main__':
print(render(int(sys.argv[1])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment