0

我想将这样的价格舍入 1.5 到 1 和 1.6 到 2 这样做

我添加了一个模型并在 lib 文件夹中为此创建了一个方法,如下所示

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

这仅适用于美元案例。我将如何为卢比做同样的事情。

任何帮助都是值得赞赏的

4

1 回答 1

1

你可以修改这一行...

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

进入...

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

这会将结果转换为整数卢比(零派萨)或整数美元(零美分)

为了更容易维护未来的货币,在 EuCentralBank 类中创建一个常量

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

然后参考那个

money = ROUNDING_CURRENCIES.include?(to_currency) ? ((decimal_money * from.cents * rate)/100).round * 100 : (decimal_money * from.cents * rate).round
于 2015-12-21T09:08:45.983 回答