From 35f6de221293da503860bfa8e003d1d1031f8576 Mon Sep 17 00:00:00 2001 From: Mikael Dalholm Date: Thu, 30 Dec 2021 14:36:24 +0100 Subject: [PATCH] Fixes #9 --- src/Money.php | 4 ++-- tests/Pest/CurrencyManagerTest.php | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Money.php b/src/Money.php index 94dff7b..efcec53 100644 --- a/src/Money.php +++ b/src/Money.php @@ -233,14 +233,14 @@ final class Money implements JsonSerializable, Arrayable, Wireable } /** Convert the money to a different currency. */ - public function convertTo(Currency|string $currency): self + public function convertTo(Currency|string $currency, float $rate = null): self { // We're converting from the current currency to the default currency, and then to the intended currency $newCurrency = currency($currency); $mathDecimalDifference = $newCurrency->mathDecimals() - currencies()->getDefault()->mathDecimals(); return new static( - (int) round($this->valueInDefaultCurrency() * $newCurrency->rate() * 10 ** $mathDecimalDifference, 0), + (int) round($this->valueInDefaultCurrency() * ($rate ?: $newCurrency->rate()) * 10 ** $mathDecimalDifference, 0), $currency ); } diff --git a/tests/Pest/CurrencyManagerTest.php b/tests/Pest/CurrencyManagerTest.php index 0bfd835..b781d09 100644 --- a/tests/Pest/CurrencyManagerTest.php +++ b/tests/Pest/CurrencyManagerTest.php @@ -126,6 +126,16 @@ test('the default currency can have any rate', function () { )->toBe('0.54 €'); }); +test('change currency rate on convertion', function () { + currencies()->add([new CZK(rate: 1), new EUR(rate: 0.5)]); + + currencies()->setDefault(CZK::class); + + expect( + money(200, 'CZK')->convertTo(EUR::class)->formatted() + )->toBe('1.00 €'); +}); + test('the getCode method accepts any currency format', function () { expect(currencies()->getCode(USD::class))->toBe('USD'); expect(currencies()->getCode(new USD))->toBe('USD');