python:在將float轉換為string時,在dot之后強制兩個零

[英]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.:

我目前正在嘗試強制python在將float轉換為字符串后保留兩個零,即:

150.00 instead of 150.0

150.00而不是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?

我對python不是很有經驗,因此只能想到一種強力方法來實現這一點。是否有內置功能來執行此操作?

Thanks

2 个解决方案

#1


8  

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

編輯:剛剛測試過,確實在3.2中工作。它也適用於舊版本的Python,而格式方法則不適用 - 但是,在可能的情況下,首選升級和使用格式方法。如果無法升級,請使用此選項。

#2


7  

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

有關字符串格式的介紹,請參閱Python教程和其中給出的鏈接。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/06/27/7259dc554823125a968b8436a613277f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com