Python 将十进制格式设置为百分比,并截断其余部分
有人能帮我格式化如下内容:Python 将十进制格式设置为百分比,并截断其余部分,python,floating-point,python-2.x,Python,Floating Point,Python 2.x,有人能帮我格式化如下内容: 0.774834437086 致: 我在寻找解决方案时遇到了麻烦。我正在使用Python2.11。乘以100可以让我接近(我仍然需要截断),但我也想凑起来。 例如,0.776834437086将四舍五入为78 round(x*100) 或 或 这可以做到: from decimal import Decimal from math import ceil d = Decimal("0.774834437086") print(d) # -> 0.7748
0.774834437086
致:
我在寻找解决方案时遇到了麻烦。我正在使用Python2.11。乘以100可以让我接近(我仍然需要截断),但我也想凑起来。
例如,0.776834437086
将四舍五入为78
round(x*100)
或
或
这可以做到:
from decimal import Decimal
from math import ceil
d = Decimal("0.774834437086")
print(d) # -> 0.774834437086
d = round(d, 2)
print(d) # -> 0.77
d2 = Decimal("0.776834437086")
print(d2) # -> 0.776834437086
d2 = ceil(d2*100)/100 # Round up to two (10**2==100) decimal places.
print(d2) # -> 0.78
请注意,0.774834437086
也会将向上取整为.78
这样做:
from decimal import Decimal
from math import ceil
d = Decimal("0.774834437086")
print(d) # -> 0.774834437086
d = round(d, 2)
print(d) # -> 0.77
d2 = Decimal("0.776834437086")
print(d2) # -> 0.776834437086
d2 = ceil(d2*100)/100 # Round up to two (10**2==100) decimal places.
print(d2) # -> 0.78
请注意,
0.774834437086
也会将四舍五入到.78
整数去掉了我不想要的讨厌的.0
,谢谢!“int”去掉了我不想要的讨厌的.0
,谢谢@尤迪什:很高兴能帮上忙。请看@yodish:很高兴能帮上忙。请看
num_1 = 0.774834437086
num_2 = 0.776834437086
percent_1 = int(round(num_1 * 100))
percent_2 = int(round(num_2 * 100))
percent_1: 77
percent_2: 78
from decimal import Decimal
from math import ceil
d = Decimal("0.774834437086")
print(d) # -> 0.774834437086
d = round(d, 2)
print(d) # -> 0.77
d2 = Decimal("0.776834437086")
print(d2) # -> 0.776834437086
d2 = ceil(d2*100)/100 # Round up to two (10**2==100) decimal places.
print(d2) # -> 0.78