diff --git a/src/Money.php b/src/Money.php index 5c59c60..9eed535 100644 --- a/src/Money.php +++ b/src/Money.php @@ -249,6 +249,15 @@ final class Money implements JsonSerializable, Arrayable, Wireable return $this->rounded()->value() - $this->value(); } + /** Get the cents from the decimal value. */ + public function cents(): static + { + return static::fromDecimal( + $this->decimal() - floor($this->decimal()), + $this->currency, + ); + } + public function toLivewire() { return $this->toArray(); diff --git a/tests/Pest/MoneyTest.php b/tests/Pest/MoneyTest.php index 6518f58..36b867c 100644 --- a/tests/Pest/MoneyTest.php +++ b/tests/Pest/MoneyTest.php @@ -210,6 +210,21 @@ test('the is method compares both the value and the currency', function () { )->toBeFalse(); }); +test('the cents from the decimal value can be fetched using the cents method', function () { + currencies()->add(CZK::class); + + expect(money(100)->cents())->toBeInstanceOf(Money::class); + + expect(money(1234, USD::class)->cents()->value())->toBe(34); + expect(money(1234, CZK::class)->cents()->value())->toBe(34); + + expect(money(100, USD::class)->cents()->value())->toBe(0); + expect(money(100, CZK::class)->cents()->value())->toBe(0); + + expect(money(123456789, USD::class)->cents()->value())->toBe(89); + expect(money(123456789, CZK::class)->cents()->value())->toBe(89); +}); + test('money can be serialized to JSON', function () { currencies()->add(CZK::class);