brick / money

A money and currency library for PHP
MIT License
1.61k stars 96 forks source link

Missing rounding on toBigInteger()? #40

Closed tomaszkane closed 3 years ago

tomaszkane commented 3 years ago

Hi, this: Money::of(1914, 'PLN', null, RoundingMode::HALF_UP)->dividedBy(12, RoundingMode::HALF_UP)->getAmount()->toInt() produce: Brick\Math\Exception\RoundingNecessaryException Rounding is necessary to represent the result of the operation at this scale.

Because it call \Brick\Math\BigDecimal::toBigInteger() without rounding mode. Why? Does I do something wrong?

Version 0.5.1 PHP 7.4.8

BenMorel commented 3 years ago

Hi, because PLN 1914 / 12 = PLN 159.50.

So getAmount() returns 159.50, which cannot be converted to an int.

The rounding mode of Money applies to the cents, not to the integral part. If what you expect is 160, you need to perform the division on the BigDecimal, i.e. after getAmount():

echo Money::of(1914, 'PLN')->getAmount()->dividedBy(12, 0, RoundingMode::HALF_UP); // 160