python: force two zeroes after dot when converting float to string
I am currently trying to force py开发者_开发百科thon to keep two zeroes after converting a float to a string, i.e.:
150.00 instead of 150.0
I am not very experienced with python and thus can only think of a brute force method to achieve this. Is there a built in functionality to do this?
Thanks
>>> "%.02f" % 150
'150.00'
Edit: Just tested, does work in 3.2 actually. It also works in older versions of Python, whilst the format methods do not - however, upgrading and using the format methods is preferred where possible. If you can't upgrade, use this.
>>> "{0:.2f}".format(150)
'150.00'
or
>>> format(150, ".2f")
'150.00'
For an introduction to string formatting, see the Python tutorial and the links given there.
精彩评论