Python保留指定位数的小数【5种方法】

02-29 1377阅读 0评论

1 %.2f’ %[变量] 【四舍五入】

可以在print()打印处使用,也可以赋值给新的变量进行输出

Python保留指定位数的小数【5种方法】,Python保留指定位数的小数【5种方法】,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,方法,学习,第1张
(图片来源网络,侵删)
# 四舍五入方法
a = 2.345566
print('%.4f'% a)
# 2.3456
print('%.3f'% a)
# 2.346
print('%.2f'% a)
# 2.35
# 赋值给新的变量
c = '%.2f'% a
print(c)
# 2.35

2 format函数【四舍五入】

可以在print()打印处使用,也可以赋值给新的变量进行输出

# 四舍五入方法
a = 2.345566
print(format(a, '.4f'))
# 2.3456
print(format(a, '.3f'))
# 2.346
# 赋值给新的变量
c = format(a, '.4f')
print(c)
# 2.3456

3 直接截断【不进行四舍五入】

3.1 先放大指定倍数,后取整,后再除以指定倍数

1 保留三位小数:先×100,后int,后÷100

a = 2.345566
c = int(a * 100) / 100
print(c)
# 2.34

2 保留三位小数:先×1000,后int,后÷1000

a = 2.345566
c = int(a * 1000) / 1000
print(c)
# 2.345

3 保留四位小数:先×10000,后int,后÷10000

a = 2.345566
c = int(a * 10000) / 10000
print(c)
# 2.3455

3.2 转为字符串进行字符串截取,截取小数点后指定的位数【不进行四舍五入】【不推荐有点麻烦】

a = 2.345566
# 进行分割
a_0 = str(a).split('.')[0]
a_1 = str(a).split('.')[1]
# 截取小数点后的
a_point = a_1[0:2] # 截取2位
# 字符串连接
a_new = a_0 + '.' + a_point
# 将string类型转换为float类型
a_new_number = float(a_new)
print(a_new_number)
# 2.34

4 round()函数【精确的四舍五入,但无法保证相同的小数位数】

round(number, ndigits=None)

返回小数点后四舍五入到ndigits精度的数字。如果ndigits被省略或为None,它将返回与其输入最近的整数。

Python保留指定位数的小数【5种方法】,Python保留指定位数的小数【5种方法】,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,方法,学习,第2张
(图片来源网络,侵删)

注意:

round()对于float的行为可能令人惊讶:例如,round(2.675,2)给出的是2.67,而不是预期的2.68。这不是一个错误:这是因为大多数十进制分数【decimal fractions】不能精确地表示为浮点值。

Python保留指定位数的小数【5种方法】

5 Numpy数组 np.set_printoptions【四舍五入】

只可以打印处使用,不可以赋值

np.set_printoptions(precision=3, suppress=True, formatter={})

precision:保留几位小数,后面不会补0

Python保留指定位数的小数【5种方法】,Python保留指定位数的小数【5种方法】,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,方法,学习,第4张
(图片来源网络,侵删)

supress:对很大/小的数都不使用科学计数法 (True)

formatter:强制格式化,后面会补0

import numpy as np
a = np.random.random(3)
print('before set precision: \n',a)
 
np.set_printoptions(precision=3, suppress=True)
print('after set precision: \n',a)
 
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print('after set formatter: \n',a)
# before set options:
# [ 0.05856348 0.5400039 0.70000603]
# after set precision:
# [ 0.059 0.54 0.7]
# after set formatter:【强制补0】
# [ 0.059 0.540 0.700]

6 总结

第 1、2、4三种方法可以进行四舍五入,可以对变量赋值

第3种方法不可以进行四舍五入,可以对变量赋值

第5种方法可以进行四舍五入,但不可以赋值


学习链接:

  • Python保留指定位数的小数
  • 详解python中的round()函数

免责声明
本网站所收集的部分公开资料来源于AI生成和互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,1377人围观)

还没有评论,来说两句吧...

目录[+]