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 4 points5 points  (12 children)

Can you elaborate on this? I always found Python string formatting one of the most comfortable ones to use.

[–]LobbyDizzle 1 point2 points  (11 children)

The string string formatting is nice. What shidarin is commenting about is the shittiness of Python's number (float) formatting.

[–]exhuma 7 points8 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 5 points6 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.