問題描述
我想格式化最多包含 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方式打印*最多*一些小數位的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!