How to have negative zero always formatted as positive zero in a python string?

后端 未结 5 698
遇见更好的自我
遇见更好的自我 2020-12-08 19:45

I have the following to format a string:

\'%.2f\' % n

If n is a negative zero (-0, -0.000 etc) the

5条回答
  •  执笔经年
    2020-12-08 20:27

    The most straightforward way is to specialcase zero in your format:

    >>> a = -0.0
    >>> '%.2f' % ( a if a != 0 else abs(a) )
    0.0
    

    However, do note that the str.format method is preferred over % substitutions - the syntax in this case (and in most simple cases) is nearly identical:

    >>> '{:.2f}'.format(a if a != 0 else abs(a))
    

    Also note that the more concise a or abs(a) doesn't seem to - even though bool(a) is False.

提交回复
热议问题