Formatting numbers

Daniel Klein danielk at
Tue May 1 21:59:13 EDT 2001

On Wed, 02 May 2001 00:10:15 GMT, "Fredrik Lundh" <fredrik at>

>Daniel Klein wrote:
>> Given an integer, 12345, how to format this to 123.45 ?
>> Ok, this is what I've come up with so far
>>     x = 12345
>>     print '%.2f' % (x,)
>you don't have to "tuplify" a single value, but tuple
>or not, it doesn't really work as specified:
>>>> print "%.2f" % (x,)
>>>> print "%.2f" % x

Ok, you're right (it's dismal how regularly you are right, F). With some
further experimentation, I came up with...

	print '%.2f' % (x/100.0,)

Anything wrong with this? It's the smallest amount of code I could muster. Of
course the solutions of taking strings are ok but violate my sensibilities for
some reason. Bjorn Pettersen had in interesting solution, ie


I wonder why this works cos 'x' sometimes shows up as a float with a large
decimal expansion, ie

	>>> x = 123456
	>>> x/100.0
	>>> str(x/100.0)

Anyway, thanks for everyone's responses! I think I can 'run' with this now; it
just bugged me that something so seemingly simple would be so elusive.


More information about the Python-list mailing list