Python 格式化数字,最多保留两位小数点,小数点末尾为 0 则删除,怎么写好?

2021-10-29 09:59:37 +08:00
 coolair

目前是这么写的,格式化了两遍,有更好的写法吗?

>>> f"{float(f'{3.100:.2f}'):g}"
'3.1'
>>> f"{float(f'{3.104:.2f}'):g}"
'3.1'
>>> f"{float(f'{3.134:.2f}'):g}"
'3.13'
1965 次点击
所在节点    问与答
34 条回复
bankroft
2021-10-29 10:01:40 +08:00
round(x, 2)
coolair
2021-10-29 10:10:37 +08:00
@bankroft 这样不行哦

>>> round(3.00, 2)
3.0
iBaoger
2021-10-29 10:28:21 +08:00
浮点型可能满足不了这个操作,转换为字符串处理
ulosggs
2021-10-29 10:28:54 +08:00
粗暴点 ('%.2f' % value).rstrip('0')
coolair
2021-10-29 10:32:04 +08:00
@ulosggs

>>> ('%.2f' % 10.00).rstrip('0')
'10.'
zjj19950716
2021-10-29 10:35:09 +08:00
@ulosggs $ python3 -c "print(('%.2f' % 3).rstrip('0'))"
3.
zpfhbyx
2021-10-29 10:38:13 +08:00
我寻思 直接 %.2f 就行了啊
zpfhbyx
2021-10-29 10:38:36 +08:00
啊哦 末位删除..忽略
wangchonglie
2021-10-29 11:13:31 +08:00
请问正文里的 :g 有什么作用呢?
krixaar
2021-10-29 11:25:57 +08:00
@coolair #5 那就再接着.rstrip('.')!
ksc010
2021-10-29 11:30:41 +08:00
@krixaar 哈哈 那不如直接 rstrip('.0')
Ediacaran
2021-10-29 11:42:50 +08:00
‘{:g}’.format(round(f, 2))
ericls
2021-10-29 11:49:53 +08:00
'.'.join(str(int(i)) for i in divmod(num * 100, 100) if i)
ericls
2021-10-29 11:52:33 +08:00
呃 不对
ipwx
2021-10-29 12:11:50 +08:00
就不能多写一个函数吗。。。


def format_num(v):
....s = f'{v:.2f}'
....if '.' in s:
........s = s.rstrip('0')
....return s
ipwx
2021-10-29 12:12:43 +08:00
In [3]: def format_num(v):
...: s = f'{v:.2f}'
...: if '.' in s:
...: s = s.rstrip('0').rstrip('.')
...: return s
...:

In [4]: format_num(100)
Out[4]: '100'

In [5]: format_num(100.1)
Out[5]: '100.1'

In [6]: format_num(100.15)
Out[6]: '100.15'

In [7]: format_num(100.159)
Out[7]: '100.16'
ipwx
2021-10-29 12:13:00 +08:00
记得 rstrip('0') 以后再 rstrip('.')
dicc
2021-10-29 12:14:27 +08:00
就 rstrip('.0')
GTim
2021-10-29 12:22:05 +08:00
@dicc 你这样会把 10.00 中的直接变成 1
coolair
2021-10-29 12:30:46 +08:00
@wangchonglie 删除后面的 0

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/811433

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX