I want chop my float number, I found php doc . First I want my value always division 10000, so my function will do it.
function floorDec($value = 0, $decimals = 2) {
$c = pow(10, $decimals);
$a1 = $value / 10000;
printf("a1: %lf, type: %s\n", $a1, gettype($a1));
$a2 = $a1 * $c;
printf("a2: %lf, type: %s\n", $a2, gettype($a2));
$a3 = floor($a2);
printf("a3: %lf, type: %s\n", $a3, gettype($a3));
$a4 = $a3 / $c;
printf("a4: %lf, type: %s\n", $a4, gettype($a4));
return $a4;
}
$a = 96684700;
var_dump(floorDec($a, 2));
Result
a1: 9668.470000, type: double
a2: 966847.000000, type: double
a3: 966846.000000, type: double
a4: 9668.460000, type: double
float(9668.46)
The variable $a3
is not I want. I have no idea why. Thanks your help.
PHP is behaving correctly. This is just a side effect of the way floating point numbers behave.
They are sometimes just a little bit inaccurate:
printf("%.99f", $a2);
prints
966846.99999999988358467817306518554687500000000000000000000
so of course if you floor()
that it'll be 966846.
Perhaps (int)round($a2);
does what you want:
966847.00000000000000000000000000000000000000000000000000000
If you need absolute precision up to a certain decimal point, have a look at these functions: https://secure.php.net/manual/en/ref.bc.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.