Print floating point values without leading zero

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

提交回复
热议问题