Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert comma to point as delimiter

How can I convert user number input from something like 11,5 to 11.5?

I have tried the following as callback:

before_validation :comma_to_delimiter

def comma_to_delimiter
  self.price.to_s.gsub(',', '.').to_f
end

But this doesn't work. I want the user to be able to type in whatever he wants as delimiter - currently, the app throws an error when the user uses a comma instead of a point.

like image 383
weltschmerz Avatar asked Jul 15 '13 10:07

weltschmerz


People also ask

How do I put dots instead of commas in Excel?

Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes.

How do I change commas to dots in PowerPoint?

Unfortunately, you cannot change the decimal separator just for PowerPoint. PowerPoint uses the separators defined in the operating system for the language region. Changing them requires changes that are permanent and system-wide.


2 Answers

In some countries comma is the standard currency delimiter and if a user types "19,99" into a form it will be saved as "19.00" unless you handle the delimiter conversion manually. I think the right way to solve this is to write custom attribute setters.

class Product < ActiveRecord::Base
  def price=(val)
    val.sub!(',', '.') if val.is_a?(String)
    self['price'] = val
  end
end
like image 187
Arctodus Avatar answered Sep 21 '22 02:09

Arctodus


What you're doing may not be the best way, so perhaps someone can answer with a better approach. But to get your line working you need to make it actually persist the change.

self.price.to_s.gsub(',', '.').to_f

Will just return the change, but that doesn't go anywhere in a callback!

self.price = self.price.to_s.gsub(',', '.').to_f
# OR
self.price.to_s.gsub!(',', '.').to_f

Will persist the change within the object.

like image 31
Matt Avatar answered Sep 21 '22 02:09

Matt