Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number with comma separators and round to 2 decimal places in Python 2?

Tags:

python-2.7

I'm sure this must be a duplicate but I can't find a clear answer on SO.

How do I output 2083525.34561 as 2,083,525.35 in Python 2?

I know about:

"{0:,f}".format(2083525.34561) 

which outputs commas but does not round. And:

"%.2f" % 2083525.34561 

which rounds, but does not add commas.

like image 628
Richard Avatar asked Apr 14 '16 14:04

Richard


People also ask

How do you round to 2 decimal places in Python?

Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.

How do you separate a number with a comma in Python?

In Python, to format a number with commas we will use “{:,}” along with the format() function and it will add a comma to every thousand places starting from left. After writing the above code (python format number with commas), Ones you will print “numbers” then the output will appear as a “ 5,000,000”.


1 Answers

Add a decimal point with number of digits .2f see the docs: https://docs.python.org/2/library/string.html#format-specification-mini-language :

In [212]: "{0:,.2f}".format(2083525.34561)  Out[212]: '2,083,525.35' 

For python 3 you can use f-strings (thanks to @Alex F):

In [2]: value = 2083525.34561 f"{value:,.2f}"   Out[2]: '2,083,525.35' 
like image 53
EdChum Avatar answered Oct 04 '22 00:10

EdChum