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.
I've tried using
before_save :strip_commas
def strip_commas
self.number = self.number.gsub(",", "")
end
but get the following error "undefined method `gsub' for 8:Fixnum" where "8" is replaced with whatever number the user enters.
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.
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
Not tested, but something resembling this should work...
You need to get at the commas while the input is still a string.
Edit: 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.try
self.number.gsub(/\D/, '')
. That is, remove everything that isn't a digit. Regexen make no distinction between integers, floats, decimals, etc. It's all strings. And Rails won't convert it correctly for you, because it just calls#to_i
or#to_f
on it.EDIT:
actually:
self.number.gsub(/[^\d\.]/, '').to_f
: everything that isn't a digit or decimal point, and convert it to a float.