5

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.

Community
  • 1
  • 1
bstpierre
  • 30,042
  • 15
  • 70
  • 103

2 Answers2

7

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'
utdemir
  • 26,532
  • 10
  • 62
  • 81
  • That's what the OP referred to as *"brute force a way around this"*, so it's not a real answer (-1). However, I'd do it this way too (+1). – Oben Sonne Jun 20 '11 at 19:54
  • +1. It's not hacky at all. Maybe using the `format()` function is a tiny bit cleaner: `format(1e-6, 'f').rstrip('0')`. – Ferdinand Beyer Jun 20 '11 at 19:55
  • @Oben Sonne, but its far better than using regex. @Ferdinand Beyer, thanks, I didn't know that, modifying answer. – utdemir Jun 20 '11 at 19:58
  • This isn't that bad; I had forgotten that `rstrip` takes an arg for the character to remove. – bstpierre Jun 20 '11 at 20:01
  • @utdemir, absolutely, that's why I would do it the same way. Nevertheless it's not really format string magic, as asked for by the OP. – Oben Sonne Jun 20 '11 at 20:03
  • 2
    The longer version of utdemirs answer: There is no format string option for this. You will have to write a solution by yourself. This is not so bad, because the solution is quite simple, as demonstrated by utdemirs use of the `rstrip` method. – Ferdinand Beyer Jun 20 '11 at 20:07
2

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))
CodeManX
  • 11,159
  • 5
  • 49
  • 70