如何舍入价格(美元和卢比)

How to round price (usd and rupee both )

我想这样舍入价格 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

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

任何帮助都是值得赞赏的

你可以修改这一行...

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

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

为了更容易维护未来的货币,在 class 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