开发者

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

开发者 https://www.devze.com 2023-02-15 13:53 出处:网络
Is there a quick way to convert a floating point number between -0.99 an开发者_开发百科d +0.99 such that it always takes up 4 characters: ie positive values go to e.g. \'0.03\' but negative values to

Is there a quick way to convert a floating point number between -0.99 an开发者_开发百科d +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?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消