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?
This version does not suffer from the bug in the previous answers where 999,999 gives you 1000.0K. It also only allows 3 significant figures and eliminates trailing 0's.
The output looks like:
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
I needed this function today, refreshed the accepted answer a bit for people with Python >= 3.6:
Edit: given the comments, you might want to change to
round(num/1000.0)
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.
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.
A more "math-y" solution is to use
math.log
:Tests: