PHP 中如何四捨五入到最接近的五的倍數?

Linda Hamilton
發布: 2024-10-27 08:39:03
原創
365 人瀏覽過

How to Round Up to the Nearest Multiple of Five in PHP?

在 PHP 中四捨五入到最接近的五的倍數

在 PHP 中處理數字時,通常需要將它們四捨五入到最接近的特定值。常見的情況是四捨五入到最接近的五的倍數。

問題陳述

尋找一個 PHP 函數,它接受一個整數作為輸入並傳回最接近的五的倍數。例如,當使用 52 呼叫時,它應該會傳回 55。

內建的 round() 函數預設不提供此功能。當使用負精度時,它會四捨五入到最接近的十次方。

要實現所需的捨入行為,可以建立一個自訂函數:

<code class="php">function roundUpToNearestMultiple($number, $multiplier = 5) {
    // Check if the number is already a multiple of the multiplier
    if ($number % $multiplier == 0) {
        return $number;
    }

    // Calculate the nearest multiple of the multiplier greater than the number
    $nextMultiple = ceil($number / $multiplier) * $multiplier;

    // Round the number up to the next multiple
    return $nextMultiple;
}</code>
登入後複製

使用範例

<code class="php">echo roundUpToNearestMultiple(52); // Outputs 55
echo roundUpToNearestMultiple(55); // Outputs 55
echo roundUpToNearestMultiple(47); // Outputs 50</code>
登入後複製

其他舍入策略

除了向上舍入到最接近的倍數之外,您可能會遇到需要不同舍入策略的場景。以下是一些變體:

1。四捨五入到下一個倍數,不含目前數字

<code class="php">function roundUpToNextMultiple($number, $multiplier = 5) {
    return roundUpToNearestMultiple($number + 1, $multiplier);
}</code>
登入後複製

2。四捨五入到最接近的倍數,包括目前數字

<code class="php">function roundToNearestMultipleInclusive($number, $multiplier = 5) {
    if ($number % $multiplier == 0) {
        return $number;
    }

    $lowerMultiple = floor($number / $multiplier) * $multiplier;
    $upperMultiple = ceil($number / $multiplier) * $multiplier;

    return round($number - $lowerMultiple) > round($upperMultiple - $number) ? $lowerMultiple : $upperMultiple;
}</code>
登入後複製

3。四捨五入為整數,然後四捨五入到最接近的倍數

<code class="php">function roundUpToIntegerAndNearestMultiple($number, $multiplier = 5) {
    $roundedNumber = ceil($number);

    if ($roundedNumber % $multiplier == 0) {
        return $roundedNumber;
    }

    return roundUpToNearestMultiple($roundedNumber, $multiplier);
}</code>
登入後複製

以上是PHP 中如何四捨五入到最接近的五的倍數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!