Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a numeric string with place-value commas into an integer?

Tags:

python

In Python, what is a clean and elegant way to convert strings like "1,374" or "21,000,000" to int values like 1374 or 21000000?

like image 939
Spike Williams Avatar asked Feb 22 '10 02:02

Spike Williams


People also ask

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

We can parse a number string with commas thousand separators into a number by removing the commas, and then use the + operator to do the conversion.

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.

Can you convert a string into a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.


1 Answers

It really depends where you get your number from.

If the number you are trying to convert comes from user input, use locale.atoi(). That way, the number will be parsed in a way that is consistent with the user's settings and thus expectations.

If on the other hand you read it, let's say, from a file, that always uses the same format, use int("1,234".replace(",", "")) or int("1.234".replace(".", "")) depending on your situation. This is not only easier to read and debug, but it's not affected by the user's locale setting, so your parser will work on any system.

like image 184
ibz Avatar answered Oct 16 '22 13:10

ibz