mirror of
https://github.com/archtechx/money.git
synced 2025-12-12 19:34:02 +00:00
Fixes #9
This commit is contained in:
parent
4474c2b115
commit
35f6de2212
2 changed files with 12 additions and 2 deletions
|
|
@ -233,14 +233,14 @@ final class Money implements JsonSerializable, Arrayable, Wireable
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Convert the money to a different currency. */
|
/** 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
|
// We're converting from the current currency to the default currency, and then to the intended currency
|
||||||
$newCurrency = currency($currency);
|
$newCurrency = currency($currency);
|
||||||
$mathDecimalDifference = $newCurrency->mathDecimals() - currencies()->getDefault()->mathDecimals();
|
$mathDecimalDifference = $newCurrency->mathDecimals() - currencies()->getDefault()->mathDecimals();
|
||||||
|
|
||||||
return new static(
|
return new static(
|
||||||
(int) round($this->valueInDefaultCurrency() * $newCurrency->rate() * 10 ** $mathDecimalDifference, 0),
|
(int) round($this->valueInDefaultCurrency() * ($rate ?: $newCurrency->rate()) * 10 ** $mathDecimalDifference, 0),
|
||||||
$currency
|
$currency
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -126,6 +126,16 @@ test('the default currency can have any rate', function () {
|
||||||
)->toBe('0.54 €');
|
)->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 () {
|
test('the getCode method accepts any currency format', function () {
|
||||||
expect(currencies()->getCode(USD::class))->toBe('USD');
|
expect(currencies()->getCode(USD::class))->toBe('USD');
|
||||||
expect(currencies()->getCode(new USD))->toBe('USD');
|
expect(currencies()->getCode(new USD))->toBe('USD');
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue