Convert string with comma to integer

RubyIntegerData Conversion

Ruby Problem Overview


Is there any neat method to convert "1,112" to integer 1112, instead of 1?

I've got one, but not neat:

"1,112".split(',').join.to_i #=> 1112

Ruby Solutions


Solution 1 - Ruby

How about this?

 "1,112".delete(',').to_i

Solution 2 - Ruby

You may also want to make sure that your code localizes correctly, or make sure the users are used to the "international" notation. For example, "1,112" actually means different numbers across different countries. In Germany it means the number a little over one, instead of one thousand and something.

Corresponding Wikipedia article is at http://en.wikipedia.org/wiki/Decimal_mark. It seems to be poorly written at this time though. For example as a Chinese I'm not sure where does these description about thousand separator in China come from.

Solution 3 - Ruby

Some more convenient

"1,1200.00".gsub(/[^0-9]/,'') 

it makes "1 200 200" work properly aswell

Solution 4 - Ruby

The following is another method that will work, although as with some of the other methods it will strip decimal places.

a = 1,112
b = a.scan(/\d+/).join().to_i => 1112

Solution 5 - Ruby

I would do using String#tr :

"1,112".tr(',','').to_i # => 1112

Solution 6 - Ruby

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

Solution 7 - Ruby

String count = count.replace(",", "");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmCYView Question on Stackoverflow
Solution 1 - RubyMichael KohlView Answer on Stackoverflow
Solution 2 - RubyYì YángView Answer on Stackoverflow
Solution 3 - RubyAlexey NovikovView Answer on Stackoverflow
Solution 4 - RubyMaheshView Answer on Stackoverflow
Solution 5 - RubyArup RakshitView Answer on Stackoverflow
Solution 6 - Rubydavidpm4View Answer on Stackoverflow
Solution 7 - RubyAjay RathoreView Answer on Stackoverflow