简体   繁体   English

在PHP中向下舍入到最接近的半个整数

[英]Round DOWN to nearest half integer in PHP

I need a PHP function that will take a float and round it down to the nearest half (x.0 or x.5). 我需要一个PHP函数,该函数需要一个浮点数并将其四舍五入到最接近的一半 (x.0或x.5)。 I found other functions that will round to the nearest fraction, but they round both ways. 我发现其他函数会四舍五入到最接近的分数,但是它们都是双向的。

The function I need can only round down. 我需要的功能只能四舍五入。

Examples 例子

7.778 -> 7.5 7.778-> 7.5

7.501 -> 7.5 7.501-> 7.5

7.49 -> 7.0 7.49-> 7.0

7.1 -> 7.0 7.1-> 7.0

$x = floor($x * 2) / 2;

我假设PHP具有floor函数: floor($num * 2) / 2应该做到这一点。

A easy solution is to use modulo operator ( fmod() function), like this : 一个简单的解决方案是使用模运算符( fmod()函数),如下所示:

function roundDown($number, $nearest){
    return $number - fmod($number, $nearest);
}

var_dump(roundDown(7.778, 0.5));
var_dump(roundDown(7.501, 0.5));
var_dump(roundDown(7.49, 0.5));
var_dump(roundDown(7.1, 0.5));

And the result : 结果:

在此处输入图片说明

The advantage it's that work with any nearest number (0.75, 22.5, 3.14 ...) 优点是可以处理任何最接近的数字(0.75、22.5、3.14 ...)

You can use the same operator to roundUp : 您可以使用相同的运算符进行roundUp:

function roundUp($number, $nearest){
    return $number + ($nearest - fmod($number, $nearest));
}

var_dump(roundUp(7.778, 0.5));
var_dump(roundUp(7.501, 0.5));
var_dump(roundUp(7.49, 0.5));
var_dump(roundUp(7.1, 0.5));

在此处输入图片说明

You can do it on that way round($number / 5, 1) * 5 the second parameter in the round() is the precision. 你可以这样做在这样round($number / 5, 1) * 5的第二个参数round()是精度。

Example with $number equal to 4.6, 4.8 and 4.75 $number等于4.6、4.8和4.75的示例

>>> round(4.6 / 5, 1) * 5;
=> 4.5
>>> round(4.8 / 5, 1) * 5;
=> 5.0
>>> round(4.75 / 5, 1) * 5;
=> 5.0

If you want you can round() down too like round($number, 1, PHP_ROUND_HALF_DOWN) check the documentation for more information https://www.php.net/manual/en/function.round.php 如果你愿意,你可以round()倒也像round($number, 1, PHP_ROUND_HALF_DOWN)检查的详细信息的文档https://www.php.net/manual/en/function.round.php

echo round($val*2) / 2;    // Done

From my job's requirements. 根据我工作的要求。 I put an function to do this. 我放置了一个函数来执行此操作。 Hope you can view it as a reference: 希望您可以将其作为参考:

function round_half_five($no) {

    $no = strval($no);
    $no = explode('.', $no);
    $decimal = floatval('0.'.substr($no[1],0,2)); // cut only 2 number
    if($decimal > 0) {
        if($decimal <= 0.5) {
            return floatval($no[0]) + 0.5;
        } elseif($decimal > 0.5 && $decimal <= 0.99) {
            return floatval($no[0]) + 1;
        }
    } else {
        return floatval($no);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM