Coder-Spirit / php-bignumbers

A robust library to handle immutable big numbers inside PHP applications
MIT License
131 stars 29 forks source link

Unexpected rounding results #73

Closed apapsch closed 2 years ago

apapsch commented 4 years ago

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:

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.)