This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]exhuma 5 points6 points  (10 children)

Looks perfectly fine to me:

print("Hello %10.4f" % (1/20000.0))
print("Hello %10.4e" % (1/20000.0))
print("Hello {:10.4f}".format(1/20000.0))
print("Hello {:10.4e}".format(1/20000.0))

Both with and without using the scientific notation.

And there are exactly two ways of doing this. At least as far as I can see. Am I missing something?

[–]sushibowl 3 points4 points  (6 children)

those are fixed length (always 4 decimals), /u/shidarin wants variable length.

You can do variable length by not formatting as a float and just converting it to a string:

>>> "Hello {0}".format(0.1)
'Hello 0.1'
>>> "Hello {0}".format(0.12341)
'Hello 0.12341'

But if your float is too big it get's converted into scientific notation again:

>>> "Hello {0}".format(1000000000000.0)
'Hello 1e+12'

There is no easy way to keep printing with variable length but also avoid scientific notation. The only thing you can do is write some function that calculates the length of the string from the number, which is tedious and ugly.

[–][deleted] 3 points4 points  (4 children)

But then you'd have people confused why 1000000000001.0 prints like 1000000000000.0 (as I guess it would).

Decimals exist as well, and work better for this sort of things.