Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid printing scientific notation in python without adding extra digits?

This question asks how to suppress scientific notation in python.

I have a series of numbers to display -- small powers of 10 -- and I'd like to display them without trailing zeros. I.e. 0.1, 0.01, and so on to 0.000001

If I do "%s" % 10 ** -6 I get '1e-06'. If I use "%f" % 10 ** -6 I get '0.000001' which is what I want.

However, "%f" % 10 ** -3 yields '0.001000' which violates the "without trailing zeros" constraint.

It's not hard to brute force a way around this (regex replacement or something), but I'm wondering if there's some format string magic I'm missing.

like image 299
bstpierre Avatar asked Jun 20 '11 19:06

bstpierre


2 Answers

It seems to me a little hacky, but you can use str.rstrip("0") to get rid of trailing zeros:

>>> "{:f}".format(10**-6).rstrip("0")
'0.000001'
>>> "{:f}".format(10**-3).rstrip("0")
'0.001'

Edit: As said in comments, there is a better way for this:

>>> format(1e-6, 'f').rstrip('0')
'0.000001'
>>> format(1e-3, 'f').rstrip('0')
'0.001'
like image 60
utdemir Avatar answered Oct 27 '22 01:10

utdemir


The simple rstrip("0") does not handle small and certain other values well, it should leave one zero after the decimal point - 0.0 instead of 0.:

def format_float(value, precision=-1):
    if precision < 0:
        f = "%f" % value
    else:
        f = "%.*f" % (precision, value)

    p = f.partition(".")

    s = "".join((p[0], p[1], p[2][0], p[2][1:].rstrip("0")))

    return s

print(format_float(3e-10))
print(format_float(3e-10, 20))
print(format_float(1.5e-6))
print(format_float(1.5e+6))
like image 44
CodeManX Avatar answered Oct 27 '22 00:10

CodeManX