Reputation: 25528
Is there a quick way to convert a floating point number between -0.99 and +0.99 such that it always takes up 4 characters: ie positive values go to e.g. '0.03' but negative values to e.g. '-.03', without the leading zero? Obviously I could do
s = '%4.2f' % n
if s[0] == '-':
s = '-%s' % s[2:]
but perhaps some stackoverflowers know of a Python shortcut?
Upvotes: 1
Views: 1632
Reputation: 76828
Well, you could do this:
"{0: 3.2f}".format(n)
The space indicates that for positive numbers, a space should be printed, and for negative numbers the sign. This way, they always take the same width.
Upvotes: 5