Print number with commas as 1000 separators in Python


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

 Live Demo

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

 Live Demo

print("{:,.2f}".format(3435.242563))

Output

Running the above code gives us the following result −

3,435.24
raja
Published on 04-Feb-2020 07:04:06
Advertisements