Search code examples
ruby-on-railscurrencymoney-rails

How to round price (usd and rupee both )


i want to round price like this 1.5 to 1 and 1.6 to 2 so to do that

i added a model and created a method for that in lib folder like this

class EuCentralBank < Money::Bank::VariableExchange
  def calculate_exchange(from, to_currency, rate)
    to_currency_money = Money::Currency.wrap(to_currency).subunit_to_unit
    from_currency_money = from.currency.subunit_to_unit
    decimal_money = BigDecimal(to_currency_money) / BigDecimal(from_currency_money)
    Rails.logger.info "From #{from} to #{to_currency}"
    money = to_currency == 'USD' ? ((decimal_money * from.cents * rate)/100).round * 100 : (decimal_money * from.cents * rate).round
    Money.new(money, to_currency)
  end
end

This is working for only dollar case. how i will do the same for rupees.

Any help is appreciatable


Solution

  • You can modify this line...

    money = to_currency == 'USD' ? ((decimal_money * from.cents * rate)/100).round * 100 : (decimal_money * from.cents * rate).round
    

    Into...

    money = ['INR', 'USD'].include?(to_currency) ? ((decimal_money * from.cents * rate)/100).round * 100 : (decimal_money * from.cents * rate).round
    

    Which will convert the result to a whole number of rupees (zero paise) or a whole number of dollars (zero cents)

    To make it easier to maintain for future currencies create a constant in class EuCentralBank

    def EuCentralBank > Money::Bank::VariableExchange
      ROUNDING_CURRENCIES = ['INR', 'USD']
      ...
    

    And then reference that

    money = ROUNDING_CURRENCIES.include?(to_currency) ? ((decimal_money * from.cents * rate)/100).round * 100 : (decimal_money * from.cents * rate).round