Search code examples
ruby-on-railscurrencycurrency-formatting

Rails round currency to nearest 5 cents with `number_to_currency`


Rails does a great job when it comes to providing view helpers that are internationally useful. This applies to currencies as well, using the helper number_to_currency. However, per documentation, I cannot find how to adjust that helper to a special case, the Swiss Franc (CHF).

The problem with the currency CHF is that the smallest coin is 5 cents, i.e. the smallest steps are CHF 1.00, 1.05, 1.10, 1.15 and so on. There is no such thing as 1.01.

The obvious solution here would be to multiply by 2, round, and divide by 2 again. However, I have a hope that number_to_currency, which is otherwise so potent, should be able to tackle this as well. Is this the case?


Solution

  • As others have noted, number_to_currency is a string formatter. You're looking for something else, not related to presentation but to making the actual number valid in your Swiss currency context.

    So I would just extend the Float class like this:

    class Float
      def rounded_to_5_cents
        ((self*2).round(1))/2
      end
    end
    # number_to_currency((55.03).rounded_to_5_cents, unit: "CHF") => CHF55.05