Skip to content

Round to nearsest #81

@BackEndTea

Description

@BackEndTea

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions