Python保留指定位数的小数
2022/3/26 11:22:34
本文主要是介绍Python保留指定位数的小数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Python保留指定位数的小数
参考:
https://blog.csdn.net/liuweiyuxiang/article/details/100574386
https://blog.csdn.net/Jerry_1126/article/details/85009810
’%.2f’ %f 方法(推荐)
f = 1.23456
print('%.4f' % f) print('%.3f' % f) print('%.2f' % f) 结果: 1.2346 1.235 1.23
这个方法会进行四舍五入
format函数(推荐)
print(format(1.23456, '.2f')) print(format(1.23456, '.3f')) print(format(1.23456, '.4f')) 1.23 1.235 1.2346
这个方法会进行四舍五入
不进行四舍五入,直接进行截断
- 可以放大指定的倍数,然后取整,然后再除以指定的倍数。
print(int(1.23456 * 1000) / 1000 )
- 使用字符串截取,截取小数点后指定的位数
>>> a = 12.345 >>> str(a).split('.')[0] + '.' + str(a).split('.')[1][:2] '12.34'
这篇关于Python保留指定位数的小数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python
- 2024-03-12python colon equals