Formatting numbers

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


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

>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,)
>12345.00
>>>> print "%.2f" % x
>12345.00

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

	str(x/100.0)

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

	>>> x = 123456
	>>> x/100.0
	1234.5599999999999
	>>> str(x/100.0)
	'1234.56'
	>>> 

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.

Dan



More information about the Python-list mailing list