Take the 2-minute tour ×

What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma?

I'd like to show 7436313 as 7.44M, and 2345 as 2,34K.

Is there some % string formatting operator available for that? Or that could be done only by actually dividing by 1000 in a loop and constructing result string step by step?

share|improve this question
add comment

4 Answers

up vote 10 down vote accepted

I don't think there's a built-in function that does that. You'll have to roll your own, e.g.:

def human_format(num):
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    # add more suffixes if you need them
    return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])

print('the answer is %s' % human_format(7436313))  # prints 'the answer is 7.44M'
share|improve this answer
add comment

No String Formatting Operator, according to the docs. I've never heard of such a thing, so you may have to roll your own, as you suggest.

share|improve this answer
add comment

I don't think there are format operators for that, but you can simply divide by 1000 until the result is between 1 and 999 and then use a format string for 2 digits after comma. Unit is a single character (or perhaps a small string) in most cases, which you can store in a string or array and iterate through it after each divide.

share|improve this answer
add comment

I don't know of any built-in capability like this, but here are a couple of list threads that may help:

http://coding.derkeiler.com/Archive/Python/comp.lang.python/2005-09/msg03327.html http://mail.python.org/pipermail/python-list/2008-August/503417.html

share|improve this answer
add comment

Your Answer


