Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string interpolation: only show necessary decimal places

If I have for example x = 40 I want the following result:

40"

For x = 2.5 the result should be like...

2.5"

So I basically want to format to at most one decimal place. I currently use this:

"{0:0.1f}\"".format(x, 1)

But this displays always exactly one decimal place, which is not really what I want...

like image 789
dom0 Avatar asked May 08 '12 22:05

dom0


3 Answers

This is reusable, can be used on str, float, or int, and will convert '' to 0:

def minimalNumber(x):
    if type(x) is str:
        if x == '':
            x = 0
    f = float(x)
    if f.is_integer():
        return int(f)
    else:
        return f

Use with:

print "{}\"".format(minimalNumber(x))

Example:

x = 2.2
print "{}\"".format(minimalNumber(x))
x = 2.0
print "{}\"".format(minimalNumber(x))

Which outputs:

2.2"
2"
like image 129
Chris Redford Avatar answered Oct 19 '22 11:10

Chris Redford


One option is something like

"{0}\"".format(str(round(x, 1) if x % 1 else int(x)))

which will display x as an integer if there's no fractional part. There's quite possibly a better way to go about this.

like image 10
Michael Mior Avatar answered Oct 19 '22 11:10

Michael Mior


Maybe not necessarily completely clean solution, but I think at least a little bit more explicit:

"{1:0.{0}f}\"".format(int(not float(x).is_integer()), x)

which may be replaced with more cryptic (based on Michael Mior rounding idea):

"{1:0.{0}f}\"".format(int(x % 1 > 0), x)

if you prefer shorter expressions (less pythonic though).

like image 3
RobertT Avatar answered Oct 19 '22 13:10

RobertT