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?
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.
You can use the str. format() to make Python recognize any objects to strings.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With