views:

96

answers:

4

Simple question, sorry I can;t figure this out. I have some numbers that are made by float(STRING) and they are displayed as xxx.0, but I want them to end in .00 if it is indeed a whole number. How would I do this?

Thanks!

EDIT:

Python saiys that float doesn't have a cal 'format()'

+10  A: 
>>> '%.2f' % 2.0
'2.00'
Alex Martelli
This formatting style is no longer to be preferred. Please check the following document: http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations
Noctis Skytower
@Noctis, if you're using Python 3 exclusively, absolutely. If you're using Python 2 (and want for example to stay compatible with that very popular deployment environment known as Google App Engine, which requires Python 2.5), percent-formatting is still best (since Python 2.5 does not support the new `format` method of strings) -- notice that the OP seems to have problems with `format` not being found, while the `%` approach works _far_ more widely.
Alex Martelli
@Alex, sounds like you expect GAE to be stuck at 2.5 for some time to come :(
gnibbler
@gnibbler, I expect the GAE team to follow their announced product roadmap, http://code.google.com/appengine/docs/roadmap.html , and there I see many crucial features and no language-version upgrades; it seems they're focusing on allowing many currently-impossible or hard tasks (via longer-running background servers, broader SSL support, reserved instances, availability/latency choices, ...) rather than allowing better syntax sugar for tasks that are already perfectly feasible -- and surely can't fault them for this choice, much as I'd like Py2.7 and 3.1 myself.
Alex Martelli
Thanks a lot Alex
gnibbler
+2  A: 

Also:

>>> "{0:.2f}".format(2.0)
'2.00'
Matt Joiner
As Python 3000 gains better recognition, this should become the standard way of formatting strings. Documentation can be found here: http://docs.python.org/py3k/library/stdtypes.html#str.format
Noctis Skytower
A: 

If you do not like the numbers to be rounded, you need to do little more:

>>> "%.2f"  % 1.99999
'2.00'
>>> "%.2f"  % (int(1.99999*100)/100.0)
'1.99'
Tony Veijalainen
A: 
>>> "{0:.2f}".format(2)
'2.00'

For more information about the {0}.format() syntax, look here: Format String Syntax

Kit