I want to append a plus sign before numbers. I am already using format specifier:
"{0:+03f}".format(x)
And I've heard about those two as well, but I don't know how to use them:
"%+d" or "%+f"
My problem with the first one is the fact that the number after format is in float type.
For example, I am making a small program to calculate quadratic function and I am not satisfied with output like this:
f(x) = 2x^2+2.000x-4.000000
Those zeros are making it looks weird.
If not above, is there any solution to get rid of zeros when there is nothing, but only zeros after the dot?
Perhaps %g
is what you're looking for?
>>> '%+g' % 2.
'+2'
>>> '%+g' % 2.1
'+2.1'
>>> '%+g' % 2.10001
'+2.10001'
The exact definition of %g
is as follows:
General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.
The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.
Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.
A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.
(source.)
Similarly with format()
:
>>> '{0:+g}'.format(2.)
'+2'
>>> '{0:+g}'.format(2.1)
'+2.1'
>>> '{0:+g}'.format(2.1001)
'+2.1001'
%+g
works but uses (very) old-style formatting. Python has evolved to provide 2 modern formatting methods:
New style formatting:
>>> "{0:+g}".format(2.00001)
'+2.00001'
>>> "{0:+g}".format(-2.00001)
'-2.00001'
>>> "{0:+g}".format(2)
'+2'
and with python 3.6+ f-strings:
>>> value = 2
>>> f"{value:+g}"
'+2'
>>> value = -2.00001
>>> f"{value:+g}"
'-2.00001'
>>> value = 2.00001
>>> f"{value:+g}"
'+2.00001'
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