Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Add Comma Into Number String

Tags:

python

string

Using Python v2, I have a value running through my program that puts out a number rounded to 2 decimal places at the end:

like this:

print ("Total cost is: ${:0.2f}".format(TotalAmount)) 

Is there a way to insert a comma value every 3 digits left of the decimal point?

Ie: 10000.00 becomes 10,000.00 or 1000000.00 becomes 1,000,000.00

Thanks for any help.

like image 707
The Woo Avatar asked Mar 03 '11 11:03

The Woo


People also ask

How do you put a comma in a string in Python?

''' if type(num) == int: return '{:,}'. format(num) elif type(num) == float: return '{:,. 2f}'. format(num) # Rounds to 2 decimal places else: print("Need int or float as input to function comma()!")


1 Answers

In Python 2.7 and 3.x, you can use the format syntax :,

>>> total_amount = 10000 >>> print("{:,}".format(total_amount)) 10,000 
>>> print("Total cost is: ${:,.2f}".format(total_amount)) Total cost is: $10,000.00 

This is documented in PEP 378 -- Format Specifier for Thousands Separator and has an example in the Official Docs "Using the comma as a thousands separator"

like image 133
Sven Marnach Avatar answered Sep 20 '22 14:09

Sven Marnach