目前是这么写的,格式化了两遍,有更好的写法吗?
>>> 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'
![]() |
1
bankroft 245 天前
round(x, 2)
|
3
iBaoger 245 天前 via Android
浮点型可能满足不了这个操作,转换为字符串处理
|
![]() |
4
ulosggs 245 天前
粗暴点 ('%.2f' % value).rstrip('0')
|
6
zjj19950716 245 天前
@ulosggs $ python3 -c "print(('%.2f' % 3).rstrip('0'))"
3. |
![]() |
7
zpfhbyx 245 天前
我寻思 直接 %.2f 就行了啊
|
![]() |
8
zpfhbyx 245 天前
啊哦 末位删除..忽略
|
![]() |
9
wangchonglie 245 天前
请问正文里的 :g 有什么作用呢?
|
12
Ediacaran 245 天前 via iPhone
‘{:g}’.format(round(f, 2))
|
![]() |
13
ericls 245 天前
'.'.join(str(int(i)) for i in divmod(num * 100, 100) if i)
|
![]() |
14
ericls 245 天前
呃 不对
|
![]() |
15
ipwx 245 天前
就不能多写一个函数吗。。。
def format_num(v): ....s = f'{v:.2f}' ....if '.' in s: ........s = s.rstrip('0') ....return s |
![]() |
16
ipwx 245 天前
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' |
![]() |
17
ipwx 245 天前
记得 rstrip('0') 以后再 rstrip('.')
|
18
dicc 245 天前
就 rstrip('.0')
|
![]() |
20
coolair OP @wangchonglie 删除后面的 0
|
21
TrembleBeforeMe 245 天前
```
>>> float(str(float(3.104))[:4]) 3.1 >>> float(str(float(3.134))[:4]) 3.13 >>> float(str(float(3.100))[:4]) 3.1 >>> ``` |
![]() |
22
CEBBCAT 245 天前
import math; print("{:g}".format(math.pi-math.pi%0.01))
|
![]() |
23
CEBBCAT 245 天前
|
![]() |
24
ipwx 245 天前
@CEBBCAT 这个不行,因为 %g 会用科学记数法。
In [4]: v = 1234567890.1234 In [5]: f'{v - v % 0.01:g}' Out[5]: '1.23457e+09' |
27
princelai 245 天前
换成字符串上正则
pat = re.compile("\d+.*?(?=(\.0+$)|(0*$))") num = [3.000,3.1000,3.061000,3.14159] for n in num: ____print(pat.search(f"{round(n,2)}").group(0)) |
28
cloudfox 245 天前
正则的话"\.?0+$"就好了
|
29
JeffGe 245 天前 via Android
你这个需求有点奇怪,工程上 3.1 和 3.10 不等价,3.10 有效数字更多,去掉后都改变原数的精度了。所以我猜原生优雅的写法是没有的,我觉得上面单独写个函数先 round 两位再处理字符串的写法就可以了,正则或者自己写逻辑处理都行,考虑科学计数法那就 split('e'),处理 [0],再 'e'.join 回去。
|
31
bomb77 245 天前
str(round(3.00000, 2)).rstrip('.0')
|
![]() |
33
c0xt30a 244 天前
打个表吧,后两位才 100 中情形,枚举出来就完了
|