xnx
xnx

Reputation: 25528

Python float to string: how to get '0.03' but '-.03'

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

Answers (2)

user35147863
user35147863

Reputation: 2605

s = ('%4.2f' % n).replace('-0','-')

Upvotes: 2

Björn Pollex
Björn Pollex

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

Related Questions