Rails money round cents up

2.8k Views Asked by At

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".

2

There are 2 best solutions below

3
Derek Wright On BEST ANSWER

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"
3
Jonathan Bowman On

Have you tried setting the rounding mode to ROUND_UP, rather than ROUND_CEILING?