Unexpected round() return
I am trying to round dow开发者_如何转开发n a number using PHP's round() function. Here is the code I am using:
$line_item_price = 13.775;
echo round($line_item_price, 2, PHP_ROUND_HALF_DOWN);
Now when I run the code like this I am hoping to get the output 13.77, except I am getting 0 (or nothing -- not sure which yet).
Now when I remove the PHP_ROUND_HALF_DOWN I get 13.78. Anyone see what I am doing wrong here? It seems like this should be working correctly.
The mode parameter was introduced in version 5.3, therefore it will not work for you. You'll have to find a custom function to do what you are looking for.
You are using a function that is not yet available in your current version of PHP. One way to solve this problem is using the floor
function.
$line_item_price = 13.775;
echo floor($line_item_price * 100) / 100;
What I'm doing here is too first multiply the value with 100 and then floor the value. This will give you a rounded down value with the precision of 2. Then to get the correct value you need to devide with 100.
The number 100 comes from the power(10, desired precision)
can you not just do:
echo round($line_item_price, 2)
?
I'm not 100% sure but I think the ROUND_HALF_DOWN etc are for fractions such as 1.5, 2.5 and integers.
Here is a way to do it:
$num = 13.775;
$tmp = intval($num*1000);
$dec = $tmp % 10;
if ($dec > 5) {
$rounded = (1+intval($tmp/10))/100;
} else {
$rounded = intval($tmp/10)/100;
}
echo $rounded,"\n";
This gives : 13.77
for $num=13.775
and 13.78
for $num=13.776
Actually, I'm kind of surprised that it works at all, since the number 13.775 is not exactly representable in floating point:
$ php -r 'printf("%.40f\n", 13.775);'
13.7750000000000003552713678800500929355621
Indeed, it seems that round()
is a bit lax about what counts as "half":
$ php -r 'echo round(13.77500000000001, 2, PHP_ROUND_HALF_DOWN) . "\n";'
13.77
Anyway, if your PHP doesn't support PHP_ROUND_HALF_DOWN
, here's a simple kluge that gives approximately the same functionality:
function round_half_down ( $num, $digits ) {
$mul = pow( 10, $digits );
return ceil( $num * $mul - 0.5 ) / $mul;
}
This does turn out to work as one would naively expect, but is slightly stricter than round()
: round_half_down(13.775, 2) == 13.77
, but round_half_down(13.77500000000001, 2) == 13.78
. Also, as a curious edge case, round_half_down(0.001, 2)
returns -0
. If you don't like that, you can always pass the return value through sprintf("%.{$digits}F")
to format it nicely.
精彩评论