Skip to content

Ability to set default context and rounding mode #59

@Padam87

Description

@Padam87

I would like to open a discussion about the possibility of implementing a way to override the context, and rounding mode of money methods.

These are hard coded all the way, and I personally find it pretty annoying, and ugly that I have to specify what I would like to do.
99.99% of the time I use my own context, and a RoundingMode::HALF_UP.

This is because in real use case scenarios the money object is always constrained by the database schema.

For example: We use 6 decimals because we work with really small, really preciese values.
Let's say the price of a single sheet of paper is 0.123456 EUR. Rounding that to 0.12 and storing it is a no-go, considering you literally need millions of these printed sometimes, and that could make a huge difference - a loss.

Calculations are always done in Rational, and cast to Money at the very end, to avoid rounding as much as possible of course, but the end is always the database scale and precision.

Long story short: DefaultContext is not viable for everyone.

public static function of($amount, $currency, ?Context $context = null, int $roundingMode = RoundingMode::UNNECESSARY) : Money
    {
        if (! $currency instanceof Currency) {
            $currency = Currency::of($currency);
        }

        if ($context === null) {
            $context = new DefaultContext();
        }

        $amount = BigNumber::of($amount);

        return self::create($amount, $currency, $context, $roundingMode);
    }

Could we make some changes here that would allow global configuration?
(This might be the rare case when I'm not against the use of a singleton for configuration)

Proposal:

public static function of($amount, $currency, ?Context $context = null, int $roundingMode = null) : Money
    {
        if (! $currency instanceof Currency) {
            $currency = Currency::of($currency);
        }

        if ($context === null) {
            $context = Configuration::getInstance()->getContext();
        }

        if ($roundingMode === null) {
            $roundingMode = Configuration::getInstance()->getRoundingMode();
        }

        $amount = BigNumber::of($amount);

        return self::create($amount, $currency, $context, $roundingMode);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions