3

I would like to have floats printed out

  • in decimal notation
  • with no trailing zeros

For instance:

1e-5    -> 0.00001
1.23e-4 -> 0.000123
1e-8    -> 0.00000001

Some things that don't work:

str(x) outputs scientific notation for small floats

format(x, 'f') and "{:f}".format(x) have fixed number of decimals, thus leave trailing zeroes

('%f' % x).rstrip('0').rstrip('.') rounds 1e-8 to 0

from decimal import Decimal
(Decimal('0.00000001000').normalize())

uses scientific notation

%0.10f requires that I know ahead of time the precision of my floats

8
  • 5
    Possible duplicate of Formatting floats in Python without superfluous zeros Mar 12, 2018 at 9:49
  • 1
    The answer to that question doesn't solve my problem. I edited my question in this regard.
    – usernumber
    Mar 12, 2018 at 10:07
  • Also from the question linekd, if you have decimals < 1e-6, you need to use a different format specifier: %0.10f could do the trick Mar 12, 2018 at 10:09
  • 1
    Well, there is a theoretical limit on how small your numbers can get, but I am sure there is pobably a practical limit how small a number you would expect and still want to output Mar 12, 2018 at 10:13
  • 1
    An IEEE double has about log10(2^53)=15.95 decimal digits of precision. So just use %.15f.
    – eugenhu
    Mar 12, 2018 at 10:18

2 Answers 2

1

If you numbers are consistently like this, you could just modify the string:

number = "1.23155e-8" # as a string
lead, power = number.split("e-")
a, b = lead.split(".")
number = "0." + "0"*(int(power)-1) + a + b

print(number)

edit: fixed it.

1
  • This works great when my floats are small enough that I know str(number) will be formatted in a "1.2345e-6" style. But if I have f=1e-1, then I need an extra step to convert to scientific notation.
    – usernumber
    Nov 5, 2019 at 17:19
1

Building on eugenhu's comment, rstrip('0') with 15 digits of precision seems to work for all your examples.

("%0.15f" % 1.e-5).rstrip('0')
Out[17]: '0.00001'

("%0.15f" % 1.e-8).rstrip('0')
Out[18]: '0.00000001'

("%0.15f" % 1.23e-4).rstrip('0')
Out[19]: '0.000123'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.