Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add thousands separator to a number that has been converted to a string in python?

in my scenario (python 2.7), i have:

str(var)

where var is a variable that sometimes requires thousands separators eg 1,500 but as you can see has been converted to a string (for concatenation purposes).

i would like to be able to print out that variable as a string with thousands separators.

i have read solutions for adding formatting to a number eg:

>>> '{:20,.2}'.format(f)
'18,446,744,073,709,551,616.00'

from https://stackoverflow.com/a/1823189/1063287

but this seems to be applicable just for a number, not for a number that has been converted to a string.

thank you.

edit: for more specific context, here is my implementation scenario:

print 'the cost = $' + str(var1) + '\n'
print 'the cost = $' + str(var2) + '\n'

and i have several 'vars'.

like image 425
user1063287 Avatar asked Mar 11 '13 18:03

user1063287


1 Answers

Do not use str(var) and concatenation, that is what .format() is for. Depending on the type of var pick one of:

'{:,}'.format(var)    # format an integer
'{:,.2f}'.format(var) # format a decimal or float

depending on the type of number you have.

>>> var = 12345678.123
>>> '{:,}'.format(int(var))  # ignore the `.123` part
'12,345,678'
>>> '{:,.2f}'.format(var)
'12,345,678.12'
like image 73
Martijn Pieters Avatar answered Nov 03 '22 00:11

Martijn Pieters