Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python和百分比_Python_Percentage_Multiplication - Fatal编程技术网

Python和百分比

Python和百分比,python,percentage,multiplication,Python,Percentage,Multiplication,在Python中有处理百分比的正确方法吗 例如,如何处理值0.01并将其显示为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 注 如果您想保留剩余的小数,只

在Python中有处理百分比的正确方法吗


例如,如何处理值
0.01
并将其显示为
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

也可以使用str.format()

1%

1%


1.4%

非常感谢您的帮助。哇,原来我吸的比我预期的还要多,如何使用变量实现这一点?假设用户输入了一个值,结果是0.19,但是我不想让它显示0.19,而是19.23或类似的东西,怎么能这样呢?如果变量是
x
,那么你会说
x*=100
Mhm,是的,我输入了它,它工作了,但我不明白,为什么?我的意思是为什么“*=”?@SteliyanPetrov操作
x*=100
是一种书写
x=x*100
percentage = 0.01
print "{0:.0f}%".format(percentage * 100)
percentage = 0.0142
print "{0:.0f}%".format(percentage * 100)
percentage = 0.0142
print "{0:.1f}%".format(percentage * 100)