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.)
But python can't represent integer negative zero.
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.
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.
Add zero:
>>> a = -0.0 >>> a + 0 0.0
which you can format:
>>> '{0:.3f}'.format(a + 0) '0.000'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With