akaunting / laravel-money

Currency formatting and conversion package for Laravel
https://akaunting.com
MIT License
732 stars 101 forks source link

Handling null amounts #100

Closed C10ne closed 6 months ago

C10ne commented 7 months ago

I'm looking for advice on what is the best way to deal with null amounts.

For example, if I have nullable field amount in database, I would do something like:

function getAmount(): ?Money
{
return $amount ? money($amount, 'USD') : null;
}

function setAmount(?float $value): void
{
$amount = $value ? money($value, 'USD')->getValue() : null;
}

Otherwise, I get exception that amount is invalid.

Is there another way to handle this case?

andrewdwallo commented 7 months ago

Always have a default value for amount, not nullable. Use 0. No amount can be interpreted as the same thing as 0.