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

后端 未结 5 706
遇见更好的自我
遇见更好的自我 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:31

    A very closely related problem is that -0.00001 is also formatted as "-0.00". That can be just as confusing. The answers above will not take care of this (except for user278064's, which needs an anchored regexp).

    It's ugly, but this is the best I can do for this case:

    import re
    re.sub (r"^-(0\.?0*)$", r"\1", "%.2f" % number)
    

提交回复
热议问题