moka
moka

Reputation: 4491

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

Upvotes: 5

Views: 4526

Answers (2)

TyrantWave
TyrantWave

Reputation: 4663

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

Upvotes: 8

Sven Marnach
Sven Marnach

Reputation: 601361

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

Upvotes: 7

Related Questions