ruby 将带逗号的字符串转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11466988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:17:38  来源:igfitidea点击:

Convert string with comma to integer

rubyintegerdata-conversion

提问by mCY

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

是否有任何巧妙的方法可以将“1,112”转换为整数 1112 而不是 1?

I've got one, but not neat:

我有一个,但不整洁:

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

回答by Michael Kohl

How about this?

这个怎么样?

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

回答by Yì Yáng

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.

您可能还想确保您的代码正确本地化,或确保用户习惯于“国际”符号。例如,“1,112”实际上表示不同国家/地区的不同数字。在德国,它的意思是比一多一点的数字,而不是一千之类的数字。

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.

相应的维基百科文章位于http://en.wikipedia.org/wiki/Decimal_mark。不过这个时候写的好像不太好。例如,作为一个 CN 人,我不确定这些关于 CN 千位分隔符的描述来自哪里。

回答by Alexey Novikov

Some more convenient

更方便一些

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

it makes "1 200 200" work properly aswell

它使“1 200 200”也能正常工作

回答by Mahesh

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

回答by davidpm4

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:

不知道性能,但它比 a 更灵活gsub,即:

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

回答by Arup Rakshit

I would do using String#tr:

我会使用String#tr

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