Print floating point values without leading zero

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.

Leave a Comment