从rails中的整数或小数中去除逗号 [英] Stripping commas from Integers or decimals in rails
问题描述
整数或小数是否有等效的 gsub?gsub 应该使用整数吗?基本上我只是想将十进制输入到 ruby 形式以及用户能够使用逗号的内容.例如,我希望用户能够输入 1,000.99.
Is there a gsub equivalent for integers or decimals? Should gsub work with integers? Basically I'm just trying to enter decimal into a ruby form and what the user to be able to use commas. For example, I want the user to be able to enter 1,000.99.
我试过使用
before_save :strip_commas
def strip_commas
self.number = self.number.gsub(",", "")
end
但得到以下错误8:Fixnum 的未定义方法`gsub'",其中8"被用户输入的任何数字替换.
but get the following error "undefined method `gsub' for 8:Fixnum" where "8" is replaced with whatever number the user enters.
推荐答案
如果您的字段是 Fixnum,则它永远不会有逗号,因为 Rails 必须将用户输入转换为数字才能将其存储在那里.
If your field is a Fixnum, it will never have commas, as Rails will have to convert the user input into a number in order to store it there.
但是,它会通过在输入字符串上调用 to_i 来实现,这不是您想要的.将普通的 setter 覆盖为类似
However, it will do that by calling to_i on the input string, which is not what you want. overriding the normal setter to something like
def price=(num)
num.gsub!(',','') if num.is_a?(String)
self[:price] = num.to_i
end
未经测试,但类似的东西应该可以工作...
Not tested, but something resembling this should work...
您需要在输入仍然是字符串时获取逗号.
You need to get at the commas while the input is still a string.
正如评论中所指出的,如果您想接受小数并创建不是整数的东西,则需要与 String.to_i
不同的转换.此外,不同国家/地区对数字标点符号有不同的约定,因此这不是一个完整的解决方案.
As noted in comments, if you want to accept decimals, and create something not an integer, you need a different conversion than String.to_i
. Also, different countries have different conventions for numeric punctuation, so this isn't a complete solution.
这篇关于从rails中的整数或小数中去除逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!