coolair
V2EX  ›  问与答

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

  •  
  •   coolair · Oct 29, 2021 · 3075 views
    This topic created in 1849 days ago, the information mentioned may be changed or developed.

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

    >>> 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'
    
    34 replies  •  2021-10-30 10:14:49 +08:00
    tribute
    tribute
    Oct 29, 2021
    1
    round(x, 2)
    coolair
    coolair
    OP
    Oct 29, 2021
    2
    @bankroft 这样不行哦

    >>> round(3.00, 2)
    3.0
    iBaoger
    iBaoger
    Oct 29, 2021 via Android
    3
    浮点型可能满足不了这个操作,转换为字符串处理
    ulosggs
    ulosggs
    Oct 29, 2021
    4
    粗暴点 ('%.2f' % value).rstrip('0')
    coolair
    coolair
    OP
    Oct 29, 2021
    5
    @ulosggs

    >>> ('%.2f' % 10.00).rstrip('0')
    '10.'
    zjj19950716
    zjj19950716
    Oct 29, 2021
    6
    @ulosggs $ python3 -c "print(('%.2f' % 3).rstrip('0'))"
    3.
    justseemore
    justseemore
    Oct 29, 2021
    7
    我寻思 直接 %.2f 就行了啊
    justseemore
    justseemore
    Oct 29, 2021
    8
    啊哦 末位删除..忽略
    wangchonglie
    wangchonglie
    Oct 29, 2021
    9
    请问正文里的 :g 有什么作用呢?
    krixaar
    krixaar
    Oct 29, 2021
    10
    @coolair #5 那就再接着.rstrip('.')!
    ksc010
    ksc010
    Oct 29, 2021
    11
    @krixaar 哈哈 那不如直接 rstrip('.0')
    Ediacaran
    Ediacaran
    Oct 29, 2021 via iPhone
    12
    ‘{:g}’.format(round(f, 2))
    ericls
    ericls
    Oct 29, 2021
    13
    '.'.join(str(int(i)) for i in divmod(num * 100, 100) if i)
    ericls
    ericls
    Oct 29, 2021
    14
    呃 不对
    ipwx
    ipwx
    Oct 29, 2021
    15
    就不能多写一个函数吗。。。


    def format_num(v):
    ....s = f'{v:.2f}'
    ....if '.' in s:
    ........s = s.rstrip('0')
    ....return s
    ipwx
    ipwx
    Oct 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'
    ipwx
    ipwx
    Oct 29, 2021
    17
    记得 rstrip('0') 以后再 rstrip('.')
    45HXlKzal6W56zUJ
    45HXlKzal6W56zUJ
    Oct 29, 2021
    18
    就 rstrip('.0')
    yemoluo
    yemoluo
    Oct 29, 2021
    19
    @dicc 你这样会把 10.00 中的直接变成 1
    coolair
    coolair
    OP
    Oct 29, 2021
    20
    @wangchonglie 删除后面的 0
    TrembleBeforeMe
    TrembleBeforeMe
    Oct 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
    >>>
    ```
    CEBBCAT
    CEBBCAT
    Oct 29, 2021
    22
    import math; print("{:g}".format(math.pi-math.pi%0.01))
    ipwx
    ipwx
    Oct 29, 2021
    24
    @CEBBCAT 这个不行,因为 %g 会用科学记数法。

    In [4]: v = 1234567890.1234

    In [5]: f'{v - v % 0.01:g}'
    Out[5]: '1.23457e+09'
    ipwx
    ipwx
    Oct 29, 2021
    25
    @CEBBCAT 而且 v- v%0.01 这种写法也太恶臭了,明明可以 round(v, 2)
    CEBBCAT
    CEBBCAT
    Oct 29, 2021 via Android
    26
    @ipwx 咳咳,饶我狗命,我只是想起来了记忆深处的 CPP 代码,像替换 round 这种操作,可以放在问题解决后再优化
    princelai
    princelai
    Oct 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))
    cloudfox
    cloudfox
    Oct 29, 2021
    28
    正则的话"\.?0+$"就好了
    JeffGe
    JeffGe
    Oct 29, 2021 via Android
    29
    你这个需求有点奇怪,工程上 3.1 和 3.10 不等价,3.10 有效数字更多,去掉后都改变原数的精度了。所以我猜原生优雅的写法是没有的,我觉得上面单独写个函数先 round 两位再处理字符串的写法就可以了,正则或者自己写逻辑处理都行,考虑科学计数法那就 split('e'),处理 [0],再 'e'.join 回去。
    45HXlKzal6W56zUJ
    45HXlKzal6W56zUJ
    Oct 29, 2021
    30
    @GTim 666666
    bomb77
    bomb77
    Oct 29, 2021
    31
    str(round(3.00000, 2)).rstrip('.0')
    sugar2845
    sugar2845
    Oct 30, 2021
    32
    @dicc 用 removesuffix ?
    c0xt30a
    c0xt30a
    Oct 30, 2021
    33
    打个表吧,后两位才 100 中情形,枚举出来就完了
    45HXlKzal6W56zUJ
    45HXlKzal6W56zUJ
    Oct 30, 2021
    34
    @sugar2845
    @bomb77 17 楼正解
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2052 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 61ms · UTC 06:16 · PVG 14:16 · LAX 22:16 · JFK 01:16
    ♥ Do have faith in what you're doing.