Python和百分比

时间:2015-07-13 13:02:04

标签: python percentage multiplication

是否有正确的方法来处理Python中的百分比?

例如,如何处理值0.01并将其显示为1%

2 个答案:

答案 0 :(得分:1)

乘以100然后转换为int

>>> int(0.01 * 100)
1

作为一项功能

def dec_to_pct(i):
    return int(i*100)

>>> dec_to_pct(0.01)
1
>>> dec_to_pct(0.07)
7
>>> dec_to_pct(0.42)
42

注意
如果您想保留剩余的小数,请将转换保留为int,例如

>>> 0.4273 * 100
42.73  # percent

答案 1 :(得分:0)

您也可以使用str.format()

percentage = 0.01
print "{0:.0f}%".format(percentage * 100)

1%

percentage = 0.0142
print "{0:.0f}%".format(percentage * 100)

1%

percentage = 0.0142
print "{0:.1f}%".format(percentage * 100)

1.4%

相关问题