From c6ef5aa54cad5b00d0b9b2edcb489b3bfc8fe4d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20=C5=A0tancl?= Date: Sun, 28 Nov 2021 18:47:59 +0100 Subject: [PATCH] addDecimal() and subtractDecimal() --- src/Money.php | 29 +++++++++++++++++++++++++---- tests/Pest/MoneyTest.php | 10 ++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/Money.php b/src/Money.php index 9eed535..980d4e2 100644 --- a/src/Money.php +++ b/src/Money.php @@ -26,6 +26,12 @@ final class Money implements JsonSerializable, Arrayable, Wireable return new self($value, $this->currency); } + /** Create a new Money instance with the same currency from a decimal value. */ + protected function newFromDecimal(float $decimal): self + { + return static::fromDecimal($decimal, $this->currency); + } + /** Create a Money instance from a decimal value. */ public static function fromDecimal(float $decimal, Currency|string $currency = null): self { @@ -49,12 +55,28 @@ final class Money implements JsonSerializable, Arrayable, Wireable ); } + /** Add money (in decimal value). */ + public function addDecimal(float $decimal): self + { + return $this->addMoney( + $this->newFromDecimal($decimal) + ); + } + /** Subtract money (in base value). */ public function subtract(int $value): self { return $this->new($this->value - $value); } + /** Subtract money (in decimal value). */ + public function subtractDecimal(float $decimal): self + { + return $this->subtractMoney( + $this->newFromDecimal($decimal) + ); + } + /** Subtract money (of another Money instance). */ public function subtractMoney(self $money): self { @@ -250,11 +272,10 @@ final class Money implements JsonSerializable, Arrayable, Wireable } /** Get the cents from the decimal value. */ - public function cents(): static + public function cents(): self { - return static::fromDecimal( - $this->decimal() - floor($this->decimal()), - $this->currency, + return $this->newFromDecimal( + $this->decimal() - floor($this->decimal()) ); } diff --git a/tests/Pest/MoneyTest.php b/tests/Pest/MoneyTest.php index 36b867c..336ea32 100644 --- a/tests/Pest/MoneyTest.php +++ b/tests/Pest/MoneyTest.php @@ -225,6 +225,16 @@ test('the cents from the decimal value can be fetched using the cents method', f expect(money(123456789, CZK::class)->cents()->value())->toBe(89); }); +test('decimal values can be added and subtracted', function () { + expect( + money(1234)->addDecimal(21.3)->value() + )->toBe(3364); + + expect( + money(1234)->subtractDecimal(8.3)->value() + )->toBe(404); +}); + test('money can be serialized to JSON', function () { currencies()->add(CZK::class);