Print floating point values without leading zero

后端 未结 13 1206
逝去的感伤
逝去的感伤 2020-11-30 05:21

Trying to use a format specifier to print a float that will be less than 1 without the leading zero. I came up with a bit of a hack but I assume there is a way to just drop

13条回答
  •  孤独总比滥情好
    2020-11-30 06:19

    I am surprised nobody suggested a more mathematical way to do it:

    n = 0.123456789
    '.%d' % (n*1e4)
    

    Looks much nicer to me. :)

    But interestingly yours is the fastest.

    $ python -mtimeit '".%d" % (0.123456789*1e4)'
    1000000 loops, best of 3: 0.809 usec per loop
    $ python -mtimeit '("%.4f"%(0.123456789)).lstrip("0")'
    1000000 loops, best of 3: 0.209 usec per loop
    $ python -mtimeit '("%.4f"%(0.123456789))[1:]'
    10000000 loops, best of 3: 0.0723 usec per loop
    

提交回复
热议问题