Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping commas from Integers or decimals in rails

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.

like image 776
Oakland510 Avatar asked Jun 30 '11 22:06

Oakland510


2 Answers

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

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.

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.

like image 53
Don Roby Avatar answered Sep 19 '22 04:09

Don Roby


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.

like image 40
Ian Avatar answered Sep 21 '22 04:09

Ian