Most Pythonic way to print *at most* some number of decimal places(大多数Pythonic方式打印*最多*一些小数位)
问题描述
我想格式化最多包含 2 个小数位的浮点数列表.但是,我不想要尾随零,也不想要尾随小数点.
I want to format a list of floating-point numbers with at most, say, 2 decimal places. But, I don't want trailing zeros, and I don't want trailing decimal points.
例如,4.001
=> 4
, 4.797
=> 4.8
, 8.992
=> 8.99
, 13.577
=> 13.58
.
So, for example, 4.001
=> 4
, 4.797
=> 4.8
, 8.992
=> 8.99
, 13.577
=> 13.58
.
简单的解决方案是('%.2f' % f).rstrip('.0')
('%.2f' % f).rstrip('0').rstrip('.')
.但是,这看起来相当丑陋,而且似乎很脆弱.任何更好的解决方案,也许有一些神奇的格式标志?
The simple solution is ('%.2f' % f).rstrip('.0')
('%.2f' % f).rstrip('0').rstrip('.')
. But, that looks rather ugly and seems fragile. Any nicer solutions, maybe with some magical format flags?
推荐答案
需要将0
和.
分开剥离;这样你就永远不会剥离自然的 0
.
You need to separate the 0
and the .
stripping; that way you won't ever strip away the natural 0
.
或者,使用 format()
函数,但这实际上归结为同一件事:
Alternatively, use the format()
function, but that really comes down to the same thing:
format(f, '.2f').rstrip('0').rstrip('.')
一些测试:
>>> def formatted(f): return format(f, '.2f').rstrip('0').rstrip('.')
...
>>> formatted(0.0)
'0'
>>> formatted(4.797)
'4.8'
>>> formatted(4.001)
'4'
>>> formatted(13.577)
'13.58'
>>> formatted(0.000000000000000000001)
'0'
>>> formatted(10000000000)
'10000000000'
这篇关于大多数Pythonic方式打印*最多*一些小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:大多数Pythonic方式打印*最多*一些小数位


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01