[英]PHP code to round decimals up
我在用
$p1 = 66.97;
$price1 = $row['Value']*$p1;
$price1 = number_format($price1, 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.9499999999999999999999999,而不是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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.