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

Instance Method Details

#*(other) ⇒ Money

Multiply by a numeric value using the stored rounding mode

Parameters:

  • numeric (Numeric)

    the multiplier

Returns:

  • (Money)

    a new Money with the product



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

Parameters:

  • other (Money)

    the money to add

Returns:

  • (Money)

    a new Money with the sum

Raises:



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

Parameters:

  • other (Money)

    the money to subtract

Returns:

  • (Money)

    a new Money with the difference

Raises:



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

Returns:

  • (Money)

    a new Money with negated cents



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

Parameters:

  • numeric (Numeric)

    the divisor

Returns:

  • (Money)

    a new Money with the quotient



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

#absMoney

Absolute value

Returns:

  • (Money)

    a new Money with the absolute value of cents



57
58
59
# File 'lib/philiprehberger/money/arithmetic.rb', line 57

def abs
  self.class.new(cents.abs, currency.code)
end