Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting long numbers as strings in python

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?

like image 836
user63503 Avatar asked Feb 23 '09 20:02

user63503


People also ask

How do you convert long to string in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.

How do I format a numeric string in Python?

You can use the str. format() to make Python recognize any objects to strings.

What is .2f in Python?

As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.

What are %d and %s in Python?

In, Python %s and %d are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator. This code will print abc 2.


1 Answers

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' 
like image 99
Adam Rosenfield Avatar answered Sep 20 '22 12:09

Adam Rosenfield