Skip to content

Commit

Permalink
Fixes archtechx#9
Browse files Browse the repository at this point in the history
  • Loading branch information
dalholm committed Dec 30, 2021
1 parent 4474c2b commit 35f6de2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Money.php
Original file line number Diff line number Diff line change
Expand Up @@ -233,14 +233,14 @@ public function valueInDefaultCurrency(): int
}

/** 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
);
}
Expand Down
10 changes: 10 additions & 0 deletions tests/Pest/CurrencyManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,16 @@
)->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');
Expand Down

0 comments on commit 35f6de2

Please sign in to comment.