Handling international currency input in Ruby on Rails

前端 未结 5 1843
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 10:06

I have an application that handles currency inputs. However, if you\'re in the US, you might enter a number as 12,345.67; in France, it might be 12.345,67

5条回答
  •  难免孤独
    2021-02-01 10:30

    We wrote this:

    class String
      def safe_parse
        self.gsub(I18n.t("number.currency.format.unit"), '').gsub(I18n.t("number.currency.format.delimiter"), '').gsub(I18n.t("number.currency.format.separator"), '.').to_f
      end
    end
    

    Of course, you will have to set the I18n.locale before using this. And it currently only converts the string to a float for the locale that was set. (In our case, if the user is on the french site, we expect the currency amount text to only have symbols and formatting pertaining to the french locale).

提交回复
热议问题