Member Avatar for tottletj

Basically I have a long list of numbers, that are never greater than 999999, and never have more than 2 decimal places, ie, most numbers look like 123456.78

But I have several numbers in this list that are less than 100000, or have only 1 decimal place, or both.
One example of which is 3434.2

I want to get python to print out this number in the same format as the others, as in i wish it to print out 003434.20

However, I'm having real problems trying to get this to happen via the format conversion specifiers. So far, I can make the second decimal place appear by simply specifying:

a=3434.2
b='%.2f' % a
print b

But when I then try to include the zeros at the start, it throws an error because the conversion i found for that

'%06d'

needs the number to be a integer, and won't allow a float. I tried converting this number into an integer to do this operator, and then back to a float again:

a=3434.2
b=a*100
c='%08d' % b
d=float(c)
e=d/100
print '%.2f' % e

However, when I make the conversion back into a float, it removes the 0's i added at the start, making the whole process pointless.

Anyone know how I can make this conversion correct?

Cheers

Use the format() method

# python >= 2.6

numbers = [ 123456.78, 3434.2 ]

for x in numbers:
    print( "The number is {num:0>9.2f}".format(num=x) )
    
""" my output -->
The number is 123456.78
The number is 003434.20
"""

See this code snippet for more http://www.daniweb.com/code/snippet232375.html :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.