Print floating point values without leading zero

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.


Here is another way:

>>> ("%.4f" % k).lstrip('0')
'.1337'

It is slightly more general than [1:] in that it also works with numbers >=1.

Neither method correctly handles negative numbers, however. The following is better in this respect:

>>> re.sub('0(?=[.])', '', ("%0.4f" % -k))
'-.1337'

Not particularly elegant, but right now I can't think of a better method.