将小数四舍五入的PHP代码
我正在使用将小数四舍五入的PHP代码,php,Php,我正在使用 $p1 = 66.97; $price1 = $row['Value']*$p1; $price1 = number_format($price1, 2, '.', ''); 进行简单计算,然后将价格显示到小数点后2位。这个很好用。我想将结果四舍五入到最接近的.05。因此,18.93将是18.95,19.57将是19.60等等。对此有什么想法吗?我正在努力。谢谢。将你的答案乘以100,然后进行5的模除运算。如果余数小于3,则减去余数,否则添加(5-余数)。接下来,除以100得到
$p1 = 66.97;
$price1 = $row['Value']*$p1;
$price1 = number_format($price1, 2, '.', '');
进行简单计算,然后将价格显示到小数点后2位。这个很好用。我想将结果四舍五入到最接近的
.05
。因此,18.93
将是18.95
,19.57
将是19.60
等等。对此有什么想法吗?我正在努力。谢谢。将你的答案乘以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'
函数rounduptany($n,$x=5){
回程(($n+x/2)/$x)*$x;
}
即。:
回声'52四舍五入至最接近的5 is'。四舍五入(52,5)。'
;
//返回“52四舍五入到最接近的5为55”
您可以执行以下操作:
$price = ceil($p1*20)/20;
您需要四舍五入到0.05
;ceil通常四舍五入到1
;所以你需要将你的数字乘以20(1/0.05=20
),让ceil做你想做的事,然后除以你得到的数字
注意浮点运算,你的结果可能是12.94999999999999999而不是12.95;因此,您应该使用sprintf('%.2f',$price)
或number\u格式将其转换为字符串,如示例中所示使用以下代码:
// 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;
18.92会是什么?18.90?18.95显然,总结一下。@Aneri这只是一个假设,我宁愿从OP那里听到。人们并不总是说他们的意思。有一个非常有用的网站叫做PHP手册!它有各种不同的语言版本,非常有用。我有没有提到过有用。
// 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;