Print floating point values without leading zero

后端 未结 13 1061
逝去的感伤
逝去的感伤 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:14

    The problem is to print a float without the leading zero, regardless of the sign of the float. The leading zero always precedes a decimal point. Split the printed float on '0.', and then rejoin the resulting list around just '.', as in below:

    >> flt = -.31415926
    

    -0.31415926

    >> '%.4f' % flt    # prints leading zero
    

    '-0.3142'

    >> '.'.join( ('%.4f' % flt).split('0.'))    # removes leading zero
    

    '-.3142'

    0 讨论(0)
  • 2020-11-30 06:15

    I'd rather go for readable and simple than anything else: Let's handle the sign and the numerics independently. And a little in-line if statement never hurt anyone.

    k = -.1337
    "".join( ["-" if k < 0 else "", ("%.4f" % abs(k)).lstrip('0')] )
    
    0 讨论(0)
  • 2020-11-30 06:16

    As much as I like cute regex tricks, I think a straightforward function is the best way to do this:

    def formatFloat(fmt, val):
      ret = fmt % val
      if ret.startswith("0."):
        return ret[1:]
      if ret.startswith("-0."):
        return "-" + ret[2:]
      return ret
    
    >>> formatFloat("%.4f", .2)
    '.2000'
    >>> formatFloat("%.4f", -.2)
    '-.2000'
    >>> formatFloat("%.4f", -100.2)
    '-100.2000'
    >>> formatFloat("%.4f", 100.2)
    '100.2000'
    

    This has the benefit of being easy to understand, partially because startswith is a simple string match rather than a regex.

    0 讨论(0)
  • 2020-11-30 06:16

    One viable option which works without regex and with negative numbers greater than 10

    k = -.1337
    ("%.4f" % k).replace("-0","-").lstrip("0")
    
    0 讨论(0)
  • 2020-11-30 06:17

    Since we're only considering > -1 to < 1 then the following edit will work.

    import re
    re.sub(r"0+\.", ".", %0.4f" % k)
    

    This will maintain the sign, only removing the digit to the left of the decimal.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题