Python保留小数点后的指定位数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43283397/article/details/102554837

这里为了可视化展示效果,将保留小数点后两位小数,若要保留多位的,替换掉数字2即可

法一:(使用round 函数)

L1 = 1.216
L2 = round(L1, 2) # 保留小数点后两位小数,会四舍五入
print(L2)

结果为: 1.22

法二:直接控制

  • 2.1. 形式1:
L1 = 1.216
L2 = "%.2f" % L1  # 四舍五入
print(L2)
  • 2.2.形式2:
L1 = 1.216
print(format(L1, ".2f"))

结果为: 1.22

法三:使用decimal模块

from decimal import *
L1 = Decimal("1.216").quantize(Decimal("0.00"))
print(L1)

结果为: 1.22

注意:
round不是简单的四舍五入

当小数点后的第一位数字>=5且需要保留整数的时候,round()取靠近的偶数

L1 = 1.516
print("L1=", round(L1))

L2 = 2.516
print("L2=", round(L2))

结果为:

L1= 2
L2= 3

其他情况正常

L3 = 1.416
print("L3=", round(L3))

L4 = 2.416
print("L4=", round(L4))

L5 = 1.416
print("L5=", round(L5, 2))

L6 = 2.416
print("L6=", round(L6, 2))

结果为:

L3= 1
L4= 2
L5= 1.42
L6= 2.42

猜你喜欢

转载自blog.csdn.net/weixin_43283397/article/details/102554837
今日推荐