From 79a7de614d522818464afb690d60ed65e0a4bcfb Mon Sep 17 00:00:00 2001 From: Frederik Bosch Date: Mon, 20 Mar 2017 13:21:40 +0100 Subject: [PATCH] multiply and divide with different locale (#361) * multiply and divide with different locale --- CHANGELOG.md | 6 ++++++ src/Money.php | 8 ++++++++ src/Number.php | 2 +- tests/MoneyTest.php | 16 ++++++++++++++++ 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82a09ed3..12f8697c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Change Log +## Unversioned + +### Fixed + +- Multiplying and dividing with a locale that use commas as separator + ## 3.0.2 - 2017-03-11 ### Fixed diff --git a/src/Money.php b/src/Money.php index 060d02c0..37a83ed4 100644 --- a/src/Money.php +++ b/src/Money.php @@ -306,6 +306,10 @@ public function multiply($multiplier, $roundingMode = self::ROUND_HALF_UP) $this->assertOperand($multiplier); $this->assertRoundingMode($roundingMode); + if (is_float($multiplier)) { + $multiplier = (string) Number::fromFloat($multiplier); + } + $product = $this->round($this->getCalculator()->multiply($this->amount, $multiplier), $roundingMode); return $this->newInstance($product); @@ -325,6 +329,10 @@ public function divide($divisor, $roundingMode = self::ROUND_HALF_UP) $this->assertOperand($divisor); $this->assertRoundingMode($roundingMode); + if (is_float($divisor)) { + $divisor = (string) Number::fromFloat($divisor); + } + if ($this->getCalculator()->compare((string) $divisor, '0') === 0) { throw new \InvalidArgumentException('Division by zero'); } diff --git a/src/Number.php b/src/Number.php index 3e704f12..1384ef02 100644 --- a/src/Number.php +++ b/src/Number.php @@ -125,7 +125,7 @@ public static function fromFloat($floatingPoint) throw new \InvalidArgumentException('Floating point expected'); } - return self::fromString(sprintf('%.8g', $floatingPoint)); + return self::fromString(sprintf('%.8F', $floatingPoint)); } /** diff --git a/tests/MoneyTest.php b/tests/MoneyTest.php index be96a002..5dbdb083 100644 --- a/tests/MoneyTest.php +++ b/tests/MoneyTest.php @@ -64,6 +64,22 @@ public function it_multiplies_the_amount($multiplier, $roundingMode, $result) $this->assertEquals((string) $result, $money->getAmount()); } + /** + * @test + */ + public function it_multiplies_the_amount_with_locale_that_uses_comma_separator() + { + setlocale(LC_ALL, 'es_ES.utf8'); + + $money = new Money(100, new Currency(self::CURRENCY)); + $money = $money->multiply(10 / 100); + + $this->assertInstanceOf(Money::class, $money); + $this->assertEquals(10, $money->getAmount()); + + setlocale(LC_ALL, null); + } + /** * @dataProvider invalidOperandExamples * @expectedException \InvalidArgumentException