Coder-Spirit/php-bignumbers

Unexpected rounding results

Closed this issue · 0 comments

The round method does not yield expected results. To reproduce:

$oneHundred = Decimal::fromInteger(100);
$grossAmount = Decimal::create(6.45);
$netAmount = $grossAmount->mul($oneHundred->div($oneHundred->add(Decimal::fromInteger(19))));
$vat = $grossAmount->sub($netAmount);
var_dump($vat->innerValue());
var_dump($vat->round(3)->innerValue());

(so basically, grossAmount - grossAmount / 1.19)

The second dump should display 1.03 but displays 1.032. Other inputs for $grossAmount which lead to rounding error are:

  • 29.95 results in 4.792 while 4.782 is expected.
  • 12.26 results in 1.962 while 1.958 is expected.

For comparison, I have performed the same calculations using a desktop calculator, GNOME calculator and https://www.geogebra.org/calculator, all of which yield the expected results.

(I have used float as input for $grossAmount because an external interface gives me a float, over which I have no control. Even with string as input, the rounding is unexpected.)