我正在使用
$p1 = 66.97;
$price1 = $row['Value']*$p1;
$price1 = number_format($price1, 2, '.', '');
进行简单的计算,然后将价格显示到小数点后 2 位。 这工作正常。我想将结果四舍五入到最接近的.05
.所以18.93
会18.95
,19.57
会19.60
等等。对此的任何想法 - 我正在挣扎。谢谢。
你可以做这样的事情:
$price = ceil($p1*20)/20;
你需要四舍五入到0.05
; ceil 通常四舍五入到 1
; 所以你需要将你的数字乘以 20 ( 1/0.05 = 20
) 让 ceil 做你想做的事,然后把你想出的数字除以;
12.95;所以你应该像你的例子一样,用sprintf('%.2f', $price)
或number_format
将其转换为字符串
将您的答案乘以 100,然后进行取模除法 5。如果余数小于 3,则减去余数,否则加(5 - 余数)。接下来,除以 100 得到最终结果。
尝试:
function roundUpToAny($n,$x=5) {
return round(($n+$x/2)/$x)*$x;
}
i.e.:
echo '52 rounded to the nearest 5 is ' . roundUpToAny(52,5) . '<br />';
// returns '52 rounded to the nearest 5 is 55'
$price = ceil($price1 * 20) / 20;
使用以下代码:
// First, multiply by 100
$price1 = $price1 * 100;
// Then, check if remainder of division by 5 is more than zero
if (($price1 % 5) > 0) {
// If so, substract remainder and add 5
$price1 = $price1 - ($price1 % 5) + 5;
}
// Then, divide by 100 again
$price1 = $price1 / 100;