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

usernumber
  • 1,958
  • 1
  • 21
  • 58
  • 5
    Possible duplicate of [Formatting floats in Python without superfluous zeros](https://stackoverflow.com/questions/2440692/formatting-floats-in-python-without-superfluous-zeros) – FlyingTeller Mar 12 '18 at 09:49
  • 1
    The answer to that question doesn't solve my problem. I edited my question in this regard. – usernumber Mar 12 '18 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 – FlyingTeller Mar 12 '18 at 10:09
  • But then I have to know ahead of time the maximal number of decimal places I will need – usernumber Mar 12 '18 at 10:11
  • 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 – FlyingTeller Mar 12 '18 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 '18 at 10:18
  • You could construct a formatting string on the fly using the logarithm of the float. – Bennett Brown Mar 12 '18 at 10:40
  • @BennettBrown What would that look like? – usernumber Nov 05 '19 at 17:13

2 Answers2

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.

nocab
  • 156
  • 1
  • 11
  • 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 05 '19 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'
Anish
  • 176
  • 2
  • 4