Handling international currency input in Ruby on Rails

前端 未结 5 1838
佛祖请我去吃肉
佛祖请我去吃肉 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:35

    You need to clean the input so that users can type pretty much whatever they want to, and you'll get something consistent to store in your database. Assuming your model is called "DoughEntry" and your attribute is "amount," and it is stored as an integer.

    Here's a method that converts a string input to cents (if the string ends in two digits following a delimeter, it's assumed to be cents). You may wish to make this smarter, but here's the concept:

    def convert_to_cents(input)
      if input =~ /^.*[\.,]\d{2}$/ 
        input.gsub(/[^\d-]/,'').to_i
      else
        "#{input.gsub(/[^\d-]/,'')}00".to_i
      end
    end
    
    >> convert_to_cents "12,345"
    => 1234500
    >> convert_to_cents "12.345,67"
    => 1234567
    >> convert_to_cents "$12.345,67"
    => 1234567
    

    Then overwrite the default "amount" accessor, passing it through that method:

    class DoughEntry << ActiveRecord::Base
    
      def amount=(input)
        write_attribute(:amount, convert_to_cents(input))
      end
    
    protected
      def convert_to_cents(input)
        if input =~ /^.*[\.,]\d{2}$/ 
          input.gsub(/[^\d-]/,'').to_i
        else
          "#{input.gsub(/[^\d-]/,'')}00".to_i
        end
      end
    end
    

    Now you're storing cents in the database. Radar has the right idea for pulling it back out.

提交回复
热议问题