4

I want a table in python to print like this:

Clearly, I want to use the .format() method, but I have long floats that look like this: 1464.1000000000001 I need the floats to be rounded, so that they look like this: 1464.10 (always two decimal places, even if both are zeros, so I can't use the round() function).

I can round the floats using "{0:.2f}".format("1464.1000000000001"), but then they do not print into nice tables.

I can put them into nice tables by doing "{0:>15}.format("1464.1000000000001"), but then they are not rounded.

Is there a way to do both? Something like "{0:>15,.2f}.format("1464.1000000000001")?

3
  • 3
    Almost there: "{0:>15.2f}".format(1464.1000000000001) is probably what you want. Commented Oct 10, 2016 at 20:30
  • Could you not use round() inside of format()? Commented Oct 10, 2016 at 20:31
  • Lots of practical examples at pyformat.info (next to the standard Python documentation). Commented Oct 10, 2016 at 20:31

2 Answers 2

9

You were almost there, just remove the comma (and pass in a float number, not a string):

"{0:>15.2f}".format(1464.1000000000001)

See the Format Specification Mini-Language section:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Breaking the above format down then:

fill: <empty>
align: <  # left
sign: <not specified>
width: 15
precision: 2
type: `f`

Demo:

>>> "{0:>15.2f}".format(1464.1000000000001)
'        1464.10'

Note that for numbers, the default alignment is to the right, so the > could be omitted.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks! I just got around the problem myself by doing two separate iterations of .format(), and it was horrible, this is much more elegant. I couldn't find anything on google about this, so thanks very much!
3
"{0:15.2f}".format(1464.1000000000001)

I always find this site useful for this stuff:

https://pyformat.info/

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.