Answer for: http://stackoverflow.com/questions/41154976/php-rounding-number-cant-round
Because round()
returns a float, and 68.45
can't be accurately represented at high precisions. In this case, 16 digits or higher.
Eg:
function test($number, $precision) {
ini_set('precision', $precision);
var_dump(
$number,
round($number, 2),
number_format($number, 2),
sprintf("%4.2f", $number)
);
echo "\n";
}
$a = 68.45999999999999;
$b = 68.46;
echo "== Precision 15 ==\n";
test($a, 15);
test($b, 15);
echo "== Precision 16 ==\n";
test($a, 16);
test($b, 16);
Output:
== Precision 15 ==
float(68.46)
float(68.46)
string(5) "68.46"
string(5) "68.46"
float(68.46)
float(68.46)
string(5) "68.46"
string(5) "68.46"
== Precision 16 ==
float(68.45999999999999)
float(68.45999999999999)
string(5) "68.46"
string(5) "68.46"
float(68.45999999999999)
float(68.45999999999999)
string(5) "68.46"
string(5) "68.46"
Use number_format()
or [s]printf()
as also illustrated in the example. However, if you are trying to accurately round a float to two digits you really should read up on how floats work...