[英]PHP code to round decimals up
I am using 我在用
$p1 = 66.97;
$price1 = $row['Value']*$p1;
$price1 = number_format($price1, 2, '.', '');
To do a simple calculation and then show the price to 2 decimal places. 做一个简单的计算,然后将价格显示为小数点后两位。 this works fine.
这很好。 I would like to round the result up to the nearest
.05
. 我想将结果四舍五入到最接近的
.05
。 So 18.93
would be 18.95
, 19.57
would be 19.60
etc. Any ideas on this - I am struggling. 因此,
18.93
是18.95
, 19.57
是19.60
等。在这个任何想法-我在挣扎。 Thanks. 谢谢。
You may do something like: 您可以执行以下操作:
$price = ceil($p1*20)/20;
You need to round up to 0.05
; 您需要四舍五入到
0.05
; ceil normally rounds up to 1
; ceil通常舍入到
1
; so you need to multiply your number by 20 ( 1/0.05 = 20
) to allow ceil do what you want, and then divide the number you came up with; 因此,您需要将数字乘以20(
1/0.05 = 20
)以允许ceil做您想做的事,然后将您想出的数字除以;
Be aware of float arithmetics, your result might really be something like 12.949999999999999999999 instead of 12.95; 要知道浮点运算,您的结果可能实际上像是12.9499999999999999999999999,而不是12.95。 so you should convert it to string with
sprintf('%.2f', $price)
or number_format
as in your example 因此,您应该像示例中那样使用
sprintf('%.2f', $price)
或number_format
将其转换为字符串
Multiply your answer by 100, then do a modulo division by 5. If the remainder is less than 3, subtract the remainder, else add (5 - remainder). 将答案乘以100,然后对5进行模除。如果余数小于3,则减去余数,否则加(5-余数)。 Next, divide by 100 to get to the final result.
接下来,除以100,得到最终结果。
Try: 尝试:
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;
Use following code: 使用以下代码:
// 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.