Search code examples
pythonstring-formatting

Print floating point values without leading zero


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 the leading zero in the format specifier. I couldn't find it in the docs.

Issue

>>> k = .1337
>>> print "%.4f" % k
'0.1337'

Hack

>>> print ("%.4f" % k) [1:]
'.1337'

Solution

  • 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.