Posted By


god_of_nothing on 03/07/11

Tagged


Statistics


Viewed 487 times
Favorited by 0 user(s)

number_to_english


/ Published in: Python
Save to your folder(s)

converts numbers to their english style


Copy this code and paste it in your HTML
  1. # this is program to convert mathematical number to alphabetical numbers
  2. # this can easily change to any language (if possible) words by modifying the lists below
  3. def translate(d):
  4. import copy
  5. lst1=['one ','two ','three ','for ','five ','six ','seven ','eight','nine','ten','eleven','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen ']
  6. lst2=['twenty ','thity ','forty ','fifty ','sixty ','seventy ','eighty ','ninety ']
  7. lst3=['one hundred ','two hundred ','three hundred ','for hundred ','five hundred ','sixe hundred ','seven hundred ','eight hundred ','nine hundred ']
  8. lst4=['thousand ','million ','billion ','trillion ']
  9. s=''
  10. t=int();y=int(d)
  11. if d==0:
  12. return 'zero'
  13. while d!=0: #--------- main LOOP
  14.  
  15. if d<20: #------if number < 20
  16. s=s+lst1[d-1]+' '
  17. return s
  18. if d>=100 and d<1000: #------if 100<number < 1000
  19. s=s+lst3[d/100-1]
  20. if d%100==0:
  21. return s
  22. while(d>99):
  23. d-=100
  24. if d>19 and d<100: #------if number < 100
  25. y=d%10
  26. t=d-(d%10)
  27. s=s+lst2[(t/10)-2]+' '
  28. if y!=0:
  29. s=s+lst1[y-1]+' '
  30. return s
  31.  
  32. if d>1000000000000: # ---------------if number < 1000 trilions
  33. first=str()
  34. first=translate(d/1000000000000)
  35. s+=first+' '+lst4[3]+' '
  36. if d%1000000000000==0:
  37. return s
  38. while d>1000000000000:
  39. d-=1000000000000
  40.  
  41. if d>1000000000: #------if number < one triliion
  42. first=str()
  43. first=translate(d/1000000000)
  44. s+=first+' '+lst4[2]+' '
  45. if d%1000000000==0:
  46. return s
  47. while d>1000000000:
  48. d-=1000000000
  49.  
  50. if d>=1000000: #------if number < one bilion
  51. first=str()
  52. first=translate(d/1000000)
  53. s=s+first+' '+lst4[1]+' '
  54. if d%1000000==0:
  55. return s
  56. while (d>1000000):
  57. d-=1000000
  58.  
  59. if d>=1000: #------if number < 1000
  60. first=str()
  61. first=translate(d/1000)
  62. s=s+first+' '+lst4[0]+' '
  63. if d%1000==0:
  64. return s
  65. while (d>1000):
  66. d-=1000
  67.  
  68. # --------------------------------
  69. if __name__=="__main__":
  70. d=raw_input('enter number or q to quit: ')
  71. if d=='q':
  72. exit()
  73. d=int(d)
  74. print translate(d)
  75. print '\n'

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.