Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I have the following to format a string:

'%.2f' % n 

If n is a negative zero (-0, -0.000 etc) the output will be -0.00.

How do I make the output always 0.00 for both negative and positive zero values of n?

(It is fairly straight forward to achieve this but I cannot find what I would call a succinct pythonic way. Ideally there is a string formatting option that I am not aware of.)

like image 494
Dan Avatar asked Jun 13 '12 08:06

Dan


People also ask

Does Python have negative zero?

But python can't represent integer negative zero.

Can 0 be a string in Python?

It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0. The len() function in Python is omnipresent - it's used to retrieve the length of every data type, with string just a first example.

How do you format a negative number in Python?

Only negative numbers are prefixed with a sign by default. You can change this by specifying the sign format option. When you use ' ' (space) for sign option, it displays a leading space for positive numbers and a minus sign for negative numbers.


1 Answers

Add zero:

>>> a = -0.0 >>> a + 0 0.0 

which you can format:

>>> '{0:.3f}'.format(a + 0) '0.000' 
like image 145
eumiro Avatar answered Oct 07 '22 02:10

eumiro