Syntax error Print number with commas as 1000 separators in Python

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
Updated on: 2020-02-04T07:05:34+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements