Module: Philiprehberger::Money::Arithmetic
- Included in:
- Philiprehberger::Money
- Defined in:
- lib/philiprehberger/money/arithmetic.rb
Overview
Arithmetic operations for Money objects
Instance Method Summary collapse
-
#*(other) ⇒ Money
Multiply by a numeric value using the stored rounding mode.
-
#+(other) ⇒ Money
Add two Money objects of the same currency.
-
#-(other) ⇒ Money
Subtract a Money object from this one.
-
#-@ ⇒ Money
Negate the amount.
-
#/(other) ⇒ Money
Divide by a numeric value using the stored rounding mode.
-
#abs ⇒ Money
Absolute value.
Instance Method Details
#*(other) ⇒ Money
Multiply by a numeric value using the stored rounding mode
31 32 33 34 35 |
# File 'lib/philiprehberger/money/arithmetic.rb', line 31 def *(other) mode = ROUNDING_MODES.fetch(rounding_mode, BigDecimal::ROUND_HALF_EVEN) result = (BigDecimal(cents.to_s) * BigDecimal(other.to_s)).round(0, mode).to_i self.class.new(result, currency.code, rounding: rounding_mode) end |
#+(other) ⇒ Money
Add two Money objects of the same currency
12 13 14 15 |
# File 'lib/philiprehberger/money/arithmetic.rb', line 12 def +(other) assert_same_currency!(other) self.class.new(cents + other.cents, currency.code) end |
#-(other) ⇒ Money
Subtract a Money object from this one
22 23 24 25 |
# File 'lib/philiprehberger/money/arithmetic.rb', line 22 def -(other) assert_same_currency!(other) self.class.new(cents - other.cents, currency.code) end |
#-@ ⇒ Money
Negate the amount
50 51 52 |
# File 'lib/philiprehberger/money/arithmetic.rb', line 50 def -@ self.class.new(-cents, currency.code) end |
#/(other) ⇒ Money
Divide by a numeric value using the stored rounding mode
41 42 43 44 45 |
# File 'lib/philiprehberger/money/arithmetic.rb', line 41 def /(other) mode = ROUNDING_MODES.fetch(rounding_mode, BigDecimal::ROUND_HALF_EVEN) result = (BigDecimal(cents.to_s) / BigDecimal(other.to_s)).round(0, mode).to_i self.class.new(result, currency.code, rounding: rounding_mode) end |
#abs ⇒ Money
Absolute value
57 58 59 |
# File 'lib/philiprehberger/money/arithmetic.rb', line 57 def abs self.class.new(cents.abs, currency.code) end |