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