Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Round to nearsest #81

Open
BackEndTea opened this issue Sep 20, 2023 · 3 comments
Open

Round to nearsest #81

BackEndTea opened this issue Sep 20, 2023 · 3 comments

Comments

@BackEndTea
Copy link

BackEndTea commented Sep 20, 2023

I have some custom logic where i want to round a price to the nearest X, and then subtract a certain amount.

e.g. in EU i want to round a price to the nearest 1 and then subtract 0.05. But for another currency i might want to round to the nearest 10, or 0.1

I have code like this to do this right now.

        $roundTo = $roundBy * pow(10, $currency->getDefaultFractionDigits());

        $roundedMoney = $money->to(new CashContext($roundTo), RoundingMode::HALF_EVEN);

        return Money::of(
            $roundedMoney->getAmount(),
            $currency,
            new DefaultContext(),
            RoundingMode::HALF_EVEN
        )
            ->plus($priceAdditon); // $priceAdditon = '-0.05';

However i was hoping there was a simpler way to do this, since now i need to know the fractionDigits etc of my currency to do the rounding. And i feel the CashContext wasn't really meant for this.

@BenMorel
Copy link
Member

Hi, your code seems OK to me, indeed CashContext was meant to be used for currency sub-units such as 0.05 €, but it will work as well for 1 € or 10 €.

You can actually simplify your code a bit, as you can chain to() methods to convert the CashContext Money back to DefaultContext:

$roundBy = 10;
$currency = Currency::of('EUR');

$roundByCents = $roundBy * 10 ** $currency->getDefaultFractionDigits(); // 1000

$money = Money::of(19, 'EUR'); // 19.00 EUR in DefaultContext

$roundedMoney = $money
    ->to(new CashContext($roundByCents), RoundingMode::HALF_EVEN) // 20.00 EUR in CashContext
    ->to(new DefaultContext()); // 20.00 EUR in DefaultContext

$priceAddition = '-0.05';

echo $roundedMoney->plus($priceAddition); // 19.95 in DefaultContext

@BackEndTea
Copy link
Author

I wonder if its a common enough use case to put this into this package itself?

Right now there are some gotchas like needing to know the currencies default fraction digits etc, and putting the money object back into its original context.

@BenMorel
Copy link
Member

I don't know if the use case is common enough, but I'm not opposed to this, what would be the signature of the method?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants