Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, is there an easy way to turn numbers with commas into an integer, and then back to numbers with commas?

Let's say I have a number like this:

8,741 or 8,741,291

How can I use python to multiply that number by 2, and then put commas back into it? I want the python function to return

17,482 and 17,482,582, in a string format.

like image 495
TIMEX Avatar asked Dec 03 '22 02:12

TIMEX


1 Answers

my_str = '1,255,000'

my_num = int(my_str.replace(',','')) #replace commas with nothing

this will return my_num = 1255000

result = my_num * 2

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
my_str = locale.format("%d", result, grouping=True)

this will return->my_str='2,510,000'

like image 130
user1474424 Avatar answered Jan 18 '23 08:01

user1474424