0

I have a rails app in which users input numbers in large quantities. They often use the thousands delimiter (e.g. 1,000,000,000) to help keep their large numbers human-readable (I don't want to disallow delimiter because doing so would increase the chance of incorrect data).

ActiveSupport/Rails has the handy method number_with_delimiter so that an int 1234567 is displayed as 1,234,567. Is there a method to do the reverse?

note: I don't want to simply strip out a comma, since commas are used as a decimal point in many locales (e.g. European)

charlie
  • 181
  • 13
  • ... and you can't just strip out commas or periods based on the locale? – Mike Quinlan May 30 '14 at 23:17
  • How does one access the delineator for that locale? – charlie May 30 '14 at 23:25
  • Good point. I guess I just don't understand the broader scope of the problem. Is it that your users are entering something into a form with commas? You're not storing amounts in the DB as strings are you? – Mike Quinlan May 30 '14 at 23:29
  • Oh gosh no. Right now in the controller it's simply `input_string.gsub(',','')` without any idea of which locale they might be in and I want to make it more extensible. The amounts are ultimately stored as floating-point numbers. – charlie May 30 '14 at 23:40

1 Answers1

0

To answer your general question, you can determine the "delimiter" (thousands-separator) and the "separator" (decimal separator) from the Rails localization system directly:

I18n.t('number.format.separator') # <= '.' on a US English system
I18n.t('number.format.delimiter') # <= ',' on a US English system

So you can do this:

better = input_string.gsub(I18n.t('number.format.delimiter'), '')

Or, if you prefer be more aggressive and remove all non-numerical and non-decimal input:

better = input_string.gsub(/[^\d#{I18n.t('number.format.separator')}]/, '')

Note, though, that the second example will also remove negative signs, if that matters to you.

It is also worth noting that ActiveRecord will do this for you:

my_model.update_attributes(some_float: "1,234.50") # <= sets some_float to 1234.5
gwcoffey
  • 5,551
  • 1
  • 18
  • 20