Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: force two zeroes after dot when converting float to string

I am currently trying to force python 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

like image 402
moka Avatar asked Jun 27 '11 10:06

moka


2 Answers

>>> "%.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.

like image 111
TyrantWave Avatar answered Nov 20 '22 13:11

TyrantWave


>>> "{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.

like image 7
Sven Marnach Avatar answered Nov 20 '22 12:11

Sven Marnach