bschleusner

May 4th, 2008, 06:15 AM

I am working on a program that needs to format a number into a string with a certain number of digits, but I am not good enough with the language to be able to format the number with a dynamic number of digits without creating ugly code.

Here is the code so far....

def formatnum(num=0,digits=0):

if (digits == 0):

return num

if (digits == 1):

retstr = '%01d' %(num)

if (digits == 2):

retstr = '%02d' %(num)

if (digits == 3):

retstr = '%03d' %(num)

if (digits == 4):

retstr = '%04d' %(num)

if (digits == 5):

retstr = '%05d' %(num)

return retstr

This is just a quick hack to make the program do what I want, but is there an easier way?

Here is the code so far....

def formatnum(num=0,digits=0):

if (digits == 0):

return num

if (digits == 1):

retstr = '%01d' %(num)

if (digits == 2):

retstr = '%02d' %(num)

if (digits == 3):

retstr = '%03d' %(num)

if (digits == 4):

retstr = '%04d' %(num)

if (digits == 5):

retstr = '%05d' %(num)

return retstr

This is just a quick hack to make the program do what I want, but is there an easier way?