[英]Rounding to nearest fraction (half, quarter, etc.)
So, I need to create the following functions but my head can't think of any possibility in PHP without complicated math. 所以,我需要创建以下函数,但是如果没有复杂的数学运算,我的脑袋就不会想到PHP的任何可能性。
I have searched on Google for 2 hours now and the only things that came up were Excel forums. 我现在已经在Google上搜索了2个小时,唯一出现的就是Excel论坛。 Is it possible with some simple lines of PHP?
是否可以使用一些简单的PHP行?
Since you're looking for fourths ( .00
, .25
, .50
, .75
), multiply your number by 4, round to nearest whole number as desired ( floor
if down, ceil
if up), then divide by 4. 因为你正在寻找四分之一 (
.00
, .25
, .50
, .75
),你的数字乘以4,根据需要舍入到最接近的整数(如果向下,则为floor
如果向上,则为ceil
),然后除以4。
1.32, down to nearest fourth : 1.32,降到最接近的第四位 :
1.32 * 4 = 5.28
1.32 * 4 = 5.28
floor(5.28) = 5.00楼层(5.28)= 5.00
5.00 / 4 = 1.255.00 / 4 = 1.25
Same principle applies for any other fractions, such as thirds or eighths ( .0
, .125
, .25
, .375
, .5
, .625
, .75
, .875
). 同样的原则适用于任何其他分数,例如三分之一或八分之一 (
.0
, .125
, .25
, .375
, .5
, .625
, .75
, .875
)。 For example: 例如:
1.77, up to nearest eighth : 1.77,最接近第八位 :
1.77 * 8 = 14.16
1.77 * 8 = 14.16
ceil(14.16) = 15.00ceil(14.16)= 15.00
15.00 / 8 = 1.87515.00 / 8 = 1.875
Just for fun, you could write a function like this: 只是为了好玩,你可以写一个这样的函数:
function floorToFraction($number, $denominator = 1)
{
$x = $number * $denominator;
$x = floor($x);
$x = $x / $denominator;
return $x;
}
echo floorToFraction(1.82); // 1
echo floorToFraction(1.82, 2); // 1.5
echo floorToFraction(1.82, 3); // 1.6666666666667
echo floorToFraction(1.82, 4); // 1.75
echo floorToFraction(1.82, 9); // 1.7777777777778
echo floorToFraction(1.82, 25); // 1.8
Please note that the answer isn't really water tight. 请注意,答案不是真的防水。 Since we're dealing with floats here it's not guaranteed that when you divide the rounded number by the denominator it returns a neatly round number.
由于我们在这里处理浮点数,因此无法保证当您将舍入数除以分母时它返回一个整齐的圆数。 It may return 1.499999999999 instead of 1.5.
它可能会返回1.499999999999而不是1.5。 It's the nature of floating point numbers.
这是浮点数的本质。
Another round is needed before returning the number from the function. 在从函数返回数字之前需要另一轮。
Just in case someone lands here from google like I did :) 以防万一有人像谷歌一样从谷歌到这里:)
看看这里的例子#3,这是你解决方案的一半 - http://php.net/manual/en/function.round.php
According to the mround()
function in Excel: 根据Excel中的
mround()
函数:
function MRound($num,$parts) {
$res = $num * $parts;
$res = round($res);
return $res /$parts;
}
echo MRound(-1.38,4);//gives -1.5
echo MRound(-1.37,4);//gives -1.25
echo MRound(1.38,4);//gives 1.5
echo MRound(1.37,4);//gives 1.25
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.