gpt4 book ai didi

python - 如何在python中打印百分比值?

转载 作者:IT老高 更新时间:2023-10-28 12:25:23 25 4
gpt4 key购买 nike

这是我的代码:

print str(float(1/3))+'%'

它显示:

0.0%

但我想得到 33%

我能做什么?

最佳答案

format支持百分比floating point precision type :

>>> print "{0:.0%}".format(1./3)
33%

如果不想整数除法,可以从__future__导入Python3的除法。 :

>>> from __future__ import division
>>> 1 / 3
0.3333333333333333

# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%

# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%

关于python - 如何在python中打印百分比值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5306756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com