Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a plus sign before positive numbers

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?

like image 968
Burak Avatar asked Dec 17 '22 19:12

Burak


2 Answers

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'
like image 183
NPE Avatar answered Dec 20 '22 07:12

NPE


%+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'
like image 21
Jean-François Fabre Avatar answered Dec 20 '22 08:12

Jean-François Fabre