class NumToWord(object): """NumToWord is a class for generating the word representation of a number""" def __init__(self, number): super(NumToWord, self).__init__() self.number = int(number) self.placeHolders = {1: " Thousand ", 2: " Million ", 3: " Billion ", 4: " Trillion ", 5: " Quadrillion ", 6: " Quintillion "} def convToWord(self): wordrep = "" splitSize = 3 chunks = __splitToChunk__(str(self.number)[::-1], splitSize) chunksize = len(chunks) print chunks for i in xrange(chunksize - 1, -1, -1): #print i threedigno = int(chunks[i]) hun = threedigno/100 #print threedigno, i if hun > 0: #print __getWordRep__(hun) wordrep+=(__getWordRep__(hun)) wordrep+=" Hundred" ten = threedigno % 100 #print ten if (ten > 0 and i == 0): if (hun > 0 or chunksize > 1): wordrep+=" and " elif (ten > 0 and i > 0 and hun > 0): wordrep+=" and " if (ten > 10 and ten <= 19): wordrep+=(" "+__getWordRep__(ten)) #wordrep+=" " else: ten = ten/10 if (ten > 0): wordrep+=(__getWordRep__(ten * 10)) #wordrep+="-" unit = int((threedigno % 100) % 10) #print unit if (unit > 0 and ten > 0): wordrep+="-" #print unit if(unit > 0): #print unit wordrep+=__getWordRep__(unit) #wordrep+=" " #print threedigno try: if threedigno > 000: #print threedigno wordrep+=self.placeHolders[i] except KeyError, e: wordrep+="" pass #raise e return wordrep+"." def __getWordRep__(number): reps = {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: "Ninty"} return reps[number] def __reverserStr__(stri): return stri[::-1] def __splitToChunk__(string, chunksize): origstringlen = len(string) chunks = [] for i in xrange(0, origstringlen, chunksize): c = __reverserStr__(string[i:min([origstringlen, (i + chunksize)])]) chunks.append(c) print i, c, min([origstringlen, (i + chunksize)]) #print chunks return chunks
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question