问题
I am fully aware of the floating point representation in binary format, so I know there are mathematical "impossibilities" when trying to perfectly represent a floating point number in any programming language. However, I would expect a programming language to follow some well known and well established rules when dealing with approximation.
Having said so, I read (here on stackoverflow too) that printf in PHP is probably the best way to "correctly truncate/approximate" a number, and - again - I am fully aware and I can easily code a one-line-function to give me the "perfect" approximation. This is just to avoid answers like "why don't you use XXX or do YYY?".
Try this:
for($i=0; $i<10; $i++) {
$k = 1.50 + $i/1000;
printf("%f %.2f<br>", $k, $k);
}
This is the output:
1.500000 1.50
1.501000 1.50
1.502000 1.50
1.503000 1.50
1.504000 1.50
1.505000 1.50
1.506000 1.51
1.507000 1.51
1.508000 1.51
1.509000 1.51
As you can easily see, 1.504 is (correctly) printed as 1.50, and 1.506 is (correctly) printed as 1.51. But why 1.505 is printed as 1.50?! It MUST BE 1.51, not 1.50!
Thank you...
回答1:
You should explicitly round the values using the round
function, so that you are able to use the argument mode
with values of:
PHP_ROUND_HALF_UP -- Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2.
PHP_ROUND_HALF_DOWN -- Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.
function:
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
see full description:
http://php.net/manual/en/function.round.php
EDIT:
for($i=0; $i<10; $i++) {
$k = 1.50 + $i/1000;
printf("%f %f<br>", $k, round($k,2,PHP_ROUND_HALF_UP));
}
来源:https://stackoverflow.com/questions/15717913/php-wrong-approximation-with-printf