Convert string with comma to integer

后端 未结 7 1795
我寻月下人不归
我寻月下人不归 2020-12-25 09:26

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 #=> 11         


        
7条回答
  •  抹茶落季
    2020-12-25 09:43

    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
    

提交回复
热议问题