I don't understand how this is even possible, output below is against all my knowledge of programming.
I'm writing a special rounding function since standard PHP rounding functions does not match my requirements.
I extracted part of complex function as separate function special_round2
, which works as I supposed to - just fine (please omit its purpose, my problem is purely about math calculation).
function special_round2($money, $decimals = 2, $presision = 2) {
//prevent invalid results
if ($decimals > $presision) {
$presision = $decimals;
}
$exponent = pow(10, $presision);
$root_extended = $money * $exponent;
//remove decimals, dont round!!! Just simple cut.
$root_int = (int) $root_extended;
var_dump(gettype($money) . "-" . $presision . "-" . $decimals . "-" . $exponent . ": " . $money . " " . $root_extended . " " . $root_int);
}
special_round2(3842.15);
When I run code above in separate php file, result are fine:
string(37) "double-2-2-100: 3842.15 384215 384215"
However, I have same code implemented as part of function in class. And the same chunk of code, gives me different results (on same input, same server, same PHP interpet).
Only difference is, that function is static
and have one optional parameter and its member of standard class, but its not part of calulation of this chunk of code.
public static function round_law($money, $decimals = 2, $presision = 2, $country_iso = self::ISO_CZE) {
//prevent invalid results
if ($decimals > $presision) {
$presision = $decimals;
}
$exponent = pow(10, $presision);
$root_extended = $money * $exponent;
//remove decimals, dont round!!! Just simple cut.
$root_int = (int) $root_extended;
var_dump(gettype($money) . "-" . $presision . "-" . $decimals . "-" . $exponent . ": " . $money . " " . $root_extended . " " . $root_int);
//some other calulation, which should be irrelevant
// ....
When I run function round_law
one of the output I got is:
string(37) "double-2-2-100: 3842.15 384215 384214"
Note that last number of dump in first case is 384215 in second case its 384214 (it's decremented by 1)
Is it php bug? How can I debug this? Am I missing something? I always thought that copy-pasted of algorithm should give me same results...
Thank you!
TL;TR
Why $root_int = (int) $root_extended;
decrement number, while inputing same value of $root_extended
?