1
0
Fork 0
mirror of https://github.com/archtechx/money.git synced 2025-12-12 11:24:03 +00:00
This commit is contained in:
Mikael Dalholm 2021-12-30 14:36:24 +01:00
parent 4474c2b115
commit 35f6de2212
2 changed files with 12 additions and 2 deletions

View file

@ -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
);
}

View file

@ -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');