Search code examples
ruby-on-railsmoney-rails

Rails money round cents up


I'm trying to round my money without cents, but I want the amount to be rounded up always (ceil).

I've done:

MoneyRails.configure do |config|
  config.rounding_mode = BigDecimal::ROUND_CEILING
end

Money.new(12345).format(:no_cents)

But it still returns "$123" instead of "$124".


Solution

  • I'm looking through the Money gem and format doesn't appear to leverage any rounding rules. Its just chopping off cents to get an "absolute" value.

    formatted = self.abs.to_s
    ...
    if rules[:no_cents] || (rules[:no_cents_if_whole] && cents % currency.subunit_to_unit == 0)
      formatted = "#{formatted.to_i}"
    end
    

    Source here: https://github.com/RubyMoney/money/blob/master/lib/money/money/formatting.rb

    Tried to find a work around for you, maybe add this as a method to your Rails Model:

    [2] pry(main)> require 'money'
    => true
    [3] pry(main)> money = Money.new(12345, 'USD')
    => #<Money fractional:12345 currency:USD>
    [6] pry(main)> "#{money.currency.symbol}#{money.to_f.ceil}"
    => "$124"