5

In Python, how can I do multiple formats at once:

So I want to make a number have no decimal places and have a thousands separator:

num = 80000.00

I want it to be 80,000

I know I can do these two things serepatly, but how would I combine them:

"{:,}".format(num) # this will give me the thousands separator
"{0:.0f}".format(num) # this will give me only two decimal places

So is it possible to combine these together??

1
  • should be "{:,.2f}" if you want the two decimal places Commented Aug 1, 2012 at 16:25

1 Answer 1

12

You can combine the two format strings. The comma goes first after the colon:

>>> "{:,.0f}".format(80000.0)
'80,000'

Note that you can also use the free format() function instead of the method str.format() when formatting only a single value:

>>> format(80000.0, ",.0f")
'80,000'

Edit: The , to include a thousands separator was introduced in Python 2.7, so the above conversions don't work in Python 2.6. In that version you will need to roll your own string formatting. Some ad-hoc code:

def format_with_commas(x):
    s = format(x, ".0f")
    j = len(s) % 3
    if j:
         groups = [s[:j]]
    else:
         groups = []
    groups.extend(s[i:i + 3] for i in range(j, len(s), 3))
    return ",".join(groups)
Sign up to request clarification or add additional context in comments.

3 Comments

I forgot to add... I am in Python 2.6... so I know that this gets a bit tricky with format... I have to specify something other wise I get a zero length operator error?
@ChristopherH: Please update your question with this information. There is no way to include a thousands spearator in Python 2.6, so the first conversion in your question won't work.
no problem... it works on another system I have using 2.7... I can figure out a workaround for the 2.6 system so I'll leave the question as is since it answered it for one system

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.