Python: 计算百分比
题目说明
假设变量a,b,其中b不等于0。限定小数后有效位数为2,求a对于b的百分比。
方法一:浮点数有效值
代码
def format_percentage(a, b):
p = 100 * a / b
if p == 0.0:
q = '0%'
else:
q = f'%.2f%%' % p
return q
示例一
print(format_percentage(31.1333, 100))
# Output is 31.13%
示例二
print(format_percentage(31, 100))
# Output is 31.00%
示例三
print(format_percentage(9.00135, 100))
# Output is 9.00%
示例四
print(format_percentage(0.00926, 100))
# Output is 0.00%
方法二:取整取余
代码
def format_percentage2(a, b):
p = int(10000