Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a number if it has commas in it as thousands separators?

Tags:

python

I have a string that represents a number which uses commas to separate thousands. How can I convert this to a number in python?

>>> int("1,000,000") 

Generates a ValueError.

I could replace the commas with empty strings before I try to convert it, but that feels wrong somehow. Is there a better way?

like image 478
dsimard Avatar asked Nov 22 '09 17:11

dsimard


People also ask

How do I change a comma separated string to a number?

To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.


2 Answers

import locale locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )  locale.atoi('1,000,000') # 1000000 locale.atof('1,000,000.53') # 1000000.53 
like image 68
unutbu Avatar answered Sep 27 '22 20:09

unutbu


There are several ways to parse numbers with thousands separators. And I doubt that the way described by @unutbu is the best in all cases. That's why I list other ways too.

  1. The proper place to call setlocale() is in __main__ module. It's global setting and will affect the whole program and even C extensions (although note that LC_NUMERIC setting is not set at system level, but is emulated by Python). Read caveats in documentation and think twice before going this way. It's probably OK in single application, but never use it in libraries for wide audience. Probably you shoud avoid requesting locale with some particular charset encoding, since it might not be available on some systems.

  2. Use one of third party libraries for internationalization. For example PyICU allows using any available locale wihtout affecting the whole process (and even parsing numbers with particular thousands separators without using locales):

    NumberFormat.createInstance(Locale('en_US')).parse("1,000,000").getLong()

  3. Write your own parsing function, if you don't what to install third party libraries to do it "right way". It can be as simple as int(data.replace(',', '')) when strict validation is not needed.

like image 41
Denis Otkidach Avatar answered Sep 27 '22 20:09

Denis Otkidach