Many times the numbers with three or more digits need to be represented suitably using comma. This is a requirement mainly in the accounting industry as well as in the finance domain. In this article we'll see how Python program can be used to insert a comma at a suitable place. We are aiming to insert comma as a thousand separator.
Format Function
The format function in python can be used with below settings to achieve this requirement.
(f"{num:,d}") : is the format specifier D is the thousand separator
Example - Integers
print(f'{1445:,d}') print(f'{140045:,d}')
Output
Running the above code gives us the following result −
1,445 140,045
Floats
With floats we have to specify with a slightly different format as shown below. The digits beyond two places after the decimal get ignored.
Example
print("{:,.2f}".format(3435.242563))
Output
Running the above code gives us the following result −
3,435.24