- Issue created by @Jaypan
- 🇮🇱Israel jsacksick
Ok, sure why not, let's add an optional scale parameter then.
- 🇷🇸Serbia bojanz
Setting $scale will truncate any extra decimals. In an eCommerce context this is rarely what you want, if you just multiplied/divided something, it would be more precise to round instead. That's why $scale wasn't exposed when we wrote the API, we wanted to guide people towards rounding.
- 🇨🇦Canada Jaypan
Thanks, I didn't know round was the better option. It would be nice to have a Price::round() helper method then. Is there any reason to not add that to Price? I'll put together a PR if there is no reason to not have it.
- 🇷🇸Serbia bojanz
There is a Rounder service. $rounder->round($price) takes the configured number of decimals for a currency and rounds to that precision.
This loading of the number of decimals is why it's a separate service.If you know the number of decimals yourself, you can always call Calculator::round() directly.
- 🇮🇱Israel jsacksick
The \Drupal calls are causing phpstan errors... What Bojan was suggesting was to invoke the Calculator directly.
The only problem is that you'd need access to the currency fraction digits, and that requires loading the currency... Which when done properly requires loading the currency from the currency storage (and that again will require adding \Drupal:: calls which isn't clean...So that lives us with this:
public function round($mode = PHP_ROUND_HALF_UP) { $currency = Currency::load($price->getCurrencyCode()); $rounded_number = Calculator::round($this->getNumber(), $currency->getFractionDigits(), $mode); return $rounded_number; }
Loading the currency like the following:
$currency = Currency::load($price->getCurrencyCode());
isn't best practice...
- 🇷🇸Serbia bojanz
If a $price->round() is desired, perhaps it take a $digits argument, and then you use Rounder if you want $digits to be auto-resolved for you?
- 🇨🇦Canada Jaypan
It sounds like it's best to just use the calculator class to round. Thanks for the explanations!