脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 如何强制限定小数点位数

Python 如何强制限定小数点位数

2021-09-23 00:35威尔莫爵士 Python

这篇文章主要介绍了Python 强制限定小数点位数的操作方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

利用''%.af''%b——其中 b 代表要限定的数字, a 代表要求限定小数点的位数,结果自动四舍五入。

例:

?
1
2
c = 1.264871331241212
print("%.3f"%c)

运行结果:

1.265

补充:Python Numpy数组格式化打印 (指定小数点位数)

Numpy数组格式化打印方法 (指定小数点位数)np.set_printoptions(precision=3, suppress=True)

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

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

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

代码:

?
1
2
3
4
5
6
7
8
9
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)

结果:

?
1
2
3
4
5
6
before set options:
 [ 0.05856348 0.5400039 0.70000603]
after set precision:
 [ 0.059 0.54 0.7]
after set formatter:
 [ 0.059 0.540 0.700]

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/qq_40229981/article/details/84143189

延伸 · 阅读

精彩推荐