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.
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'
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))
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