这是我的代码:
print str(float(1/3))+'%'
它显示:
0.0%
但我想得到
33%
我能做什么?
format
支持百分比浮点精度类型:
>>> 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%
.format()
格式方法有一种更方便的“百分比”格式选项:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
只是为了完整起见,因为我注意到没有人建议这种简单的方法:
>>> print("%.0f%%" % (100 * 1.0/3))
33%
详情:
%.0f
代表“打印小数点后 0 位的浮点数”,所以 %.2f
会打印 33.33
%%
打印文字 %
。比原来的干净一点+'%'
1.0
而不是 1
负责强制部门浮动,所以不再有 0.0
只需添加 Python 3 f-string 解决方案
prob = 1.0/3.0
print(f"{prob:.0%}") # 33%
print(f"{prob:.2%}") # 33.33%
您正在除以整数然后转换为浮点数。改为除以浮点数。
作为奖励,使用这里描述的很棒的字符串格式化方法:http://docs.python.org/library/string.html#format-specification-mini-language
指定百分比转换和精度。
>>> float(1) / float(3)
[Out] 0.33333333333333331
>>> 1.0/3.0
[Out] 0.33333333333333331
>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'
>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'
一颗伟大的宝石!
然后你想这样做:
print str(int(1.0/3.0*100))+'%'
.0
将它们表示为浮点数,然后 int()
再次将它们四舍五入为整数。
我用这个
ratio = round(1/3, 2)
print(f"{ratio} %")
output: 0.33 %
这就是我为让它工作所做的,工作起来很有魅力
divideing = a / b
percentage = divideing * 100
print(str(float(percentage))+"%")