Microsoft
Software
Hardware
Network
Question : How can I add leading and following zero's to a floating point number?
I'm trying to display a string in the format 000.000 which will represent a calculated number
in my program. The calculated numbers will not always have 3 digits on each side of the decimal place.
for instance here are a couple of example numbers
1.22
22.34
So what I need to do is make a string from the number but the string needs to have left and right padding
of zeros, so the numbers above would be
001.220
022.340
I was trying to copy the numberString into the defaultString by position listed below, but
apparently Strings are immutable and I can't insert a substring. I don't know if there is a way
to add the padding to the number first before I make it a string or a way to do it as a string.
Either way I'm a little stumped since I've only been using Python a few weeks.
numberString = str(1.22)
decimalPosition = numberString.find('.')
length = len(numberString)
defaultString = "000.000"
startPosition = length - 1 - decimalPosition #position in default string to start
for s in range(0,decimalPosition,1)
:
defaultString[startPositio
n] = numberString[s]
startPosition = startPostion + 1
for s in range(decimalPosition+1,le
ngth,1):
defaultString[startPositio
n] = numberString[s]
startPosition = startPostion + 1
Answer : How can I add leading and following zero's to a floating point number?
Try this:
"%07.3f" % number
For example:
"%07.3f" % 1.0 = '001.000'
Random Solutions
Cleaning Up Offline Files
Protecting against injection attacks
Change domain name of internal network
Using SetHostName in IIS 6.0
Installation of vgetty in Win XP
Differences between Sharepoint Portal Server 2007 and Windows Sharepoint Services
Cannot import calendar and contacts to Exchange 2003 mailbox with Outlook XP
SBS 2008 SQL Log Huge, can't login to fix it
Having 'No Records Found' display in listbox
Removing Icons at Quick Launch Tray