In this program, we need to print the output of a given integer in international place value format and put commas at the appropriate place, from the right. Let’s see an example of how to print numbers with commas as thousands of separators in Python.
Examples
Input : 1000000
Output : 1,000,000
Input : 1000
Output : 1,00
Method 1: using f-string
F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting. The inner part within the curly brackets : , says to format the number and use commas as thousand separators.
Example 1:
Format the number and add commas as a thousand separators to use the ‘,d’ formatting syntax in the format() function.
Python3
num = 1000000000
print(f"{num:,d}")
|
Example 2:
F-string with replaces function.
Python3
res = f'{10000000:,}'.replace('.',',')
print(res)
|
Method 2: string.format()
Here, we have used the “{:,}” along with the format() function to add commas every thousand places starting from left. This is introduced in Python and it automatically adds a comma on writing the following syntax.
Example 1:
Numbers with an integer.
Python3
res = '{:,}'.format(1000000)
print(res)
|
Example 2:
Numbers with decimal.
Python3
num = 123456.1234567
res = '{:,.2f}'.format(num)
print(res)
|
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
21 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...