Skip to content
This repository has been archived by the owner on Jan 24, 2018. It is now read-only.

Commit

Permalink
Implement rounding in multiply()
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianbergmann committed Oct 19, 2013
1 parent c55b1ce commit fcf91ed
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
25 changes: 22 additions & 3 deletions src/Money.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ class Money
*/
private $currency;

/**
* @var integer[]
*/
private static $roundingModes = array(
PHP_ROUND_HALF_UP,
PHP_ROUND_HALF_DOWN,
PHP_ROUND_HALF_EVEN,
PHP_ROUND_HALF_ODD
);

/**
* @param integer $amount
* @param \SebastianBergmann\Money\Currency $currency
Expand Down Expand Up @@ -151,12 +161,21 @@ public function negate()
* Returns a new Money object that represents the monetary value
* of this Money object multiplied by a given factor.
*
* @param float $factor
* @param float $factor
* @param integer $roundingMode
* @return \SebastianBergmann\Money\Money
*/
public function multiply($factor)
public function multiply($factor, $roundingMode = PHP_ROUND_HALF_UP)
{
return $this->newMoney($factor * $this->amount);
if (!in_array($roundingMode, self::$roundingModes)) {
throw new InvalidArgumentException(
'$roundingMode must be a valid rounding mode (PHP_ROUND_*)'
);
}

return $this->newMoney(
intval(round($factor * $this->amount, 0, $roundingMode))
);
}

/**
Expand Down
10 changes: 10 additions & 0 deletions tests/MoneyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,16 @@ public function testCanBeMultipliedByAFactor()
$this->assertEquals(2, $b->getAmount());
}

/**
* @covers SebastianBergmann\Money\Money::multiply
* @expectedException SebastianBergmann\Money\InvalidArgumentException
*/
public function testExceptionIsRaisedWhenMultipliedUsingInvalidRoundingMode()
{
$a = new Money(1, new Currency('EUR'));
$b = $a->multiply(2, NULL);
}

/**
* @covers SebastianBergmann\Money\Money::allocateToTargets
* @covers SebastianBergmann\Money\Money::newMoney
Expand Down

0 comments on commit fcf91ed

Please sign in to comment.