我有以下代码将我的金额四舍五入到最接近的美元:
switch ($amazonResult['SalesRank']) {
case ($amazonResult['SalesRank'] < 1 || trim($amazonResult['SalesRank'])===''|| !isset($amazonResult['SalesRank']) || $amazonResult['SalesRank']=== null):
$Price=((float) $lowestAmazonPrice) * 0.05;
$payPrice = round($Price, 0); //to round the price up or down to the nearest $
break;
case ($amazonResult['SalesRank'] > 0 && $amazonResult['SalesRank'] <= 15000):
$Price=((float) $lowestAmazonPrice) * 0.20;
$payPrice = round($Price, 0); //to round the price up or down to the nearest $
break;
据我所知,如果我使用圆形($ Price,2);我将有2位小数,但有没有办法舍入到最接近的50美分?
答案 0 :(得分:24)
一些简单的数学应该可以解决问题。而不是四舍五入到最接近的50美分,而是将$price
加倍到最接近的美元,然后是它的一半。
$payprice = round($Price * 2, 0)/2;
答案 1 :(得分:13)
乘以2,在上面的数字中舍入到0,你想要舍入到.5(在你的情况下舍入到小数位数),除以2.
这将使你四舍五入到最接近的.5,加上0并且你有四舍五入到最接近的.50。
如果你想要最近的.25做同样的但是乘以除以4。
答案 2 :(得分:4)
function roundnum($num, $nearest){
return round($num / $nearest) * $nearest;
}
例如:
$num = 50.55;
$nearest = .50;
echo roundnum($num, $nearest);
返回
50.50
这可用于圆形到任何东西,5cents,25cents等......
对ninjured的信任: http://forums.devshed.com/php-development-5/round-to-the-nearest-5-cents-537959.html
答案 3 :(得分:1)
请注意,如果使用floor而不是round,则需要额外的一轮,因为浮点数的内部精度。
function roundnum($num, $nearest){
return floor(round($num / $nearest)) * $nearest;
}
$num = 16.65;
$nearest = .05;
echo roundnum($num, $nearest);
否则它将返回16.60而不是16.65
答案 4 :(得分:0)
来自手册:echo round(1.95583, 2); // 1.96
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
val
The value to round
precision
The optional number of decimal digits to round to.
mode
One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD.
只需更改为:echo round(1.54*2, 0)/2; // 1.5
答案 5 :(得分:0)
将数字除以最近,做ceil,然后乘以最近减去有效数字。
function rndnum($num, $nearest){
return ceil($num / $nearest) * $nearest;
}
实施例
echo rndnum(95.5,10)返回100
echo rndnum(94.5,1)返回95