在PHP中四舍五入到五的近似倍数 [英] Round up to nearest multiple of five in PHP
本文介绍了在PHP中四舍五入到五的近似倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过了 round()
$ b
echo round(94,-1); // 90
它返回 90 ,但我想要 95 。
谢谢。
解决方案
在很多方面,取决于您的首选舍入约定:
1。四舍五入到 next 5的倍数,排除当前数字
行为:50个输出55,52个输出55
函数roundUpToAny($ n,$ x = 5){
return round(($ n + $ x / 2 )/ $ X)* $ X;
}
2。四舍五入为5的倍数,包括当前数字
行为:50个输出50,52个输出55,50.25个输出50 函数roundUpToAny($ n,$ x = 5){
return(round($ n )%$ x === 0)? ($ n):round(($ n + $ x / 2)/ $ x)* $ x;
}
函数roundUpToAny($ n,$ x = 5){
return(round($ n )%$ x === 0)? ($ n):round(($ n + $ x / 2)/ $ x)* $ x;
}
3。四舍五入到整数,然后到5的最接近倍数
行为:50个输出50,52个输出55,50.25个输出55 p>
函数roundUpToAny($ n,$ x = 5){
return(ceil($ n)%$ x == = 0)? ceil($ n):round(($ n + $ x / 2)/ $ x)* $ x;
}
I want a php function which returns 55 when calling it with 52.
I've tried the round()
function:
echo round(94, -1); // 90
It returns 90 but I want 95.
Thanks.
解决方案
This can be accomplished in a number of ways, depending on your preferred rounding convention:
1. Round to the next multiple of 5, exclude the current number
Behaviour: 50 outputs 55, 52 outputs 55
function roundUpToAny($n,$x=5) {
return round(($n+$x/2)/$x)*$x;
}
2. Round to the nearest multiple of 5, include the current number
Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 50
function roundUpToAny($n,$x=5) {
return (round($n)%$x === 0) ? round($n) : round(($n+$x/2)/$x)*$x;
}
3. Round up to an integer, then to the nearest multiple of 5
Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 55
function roundUpToAny($n,$x=5) {
return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x;
}
这篇关于在PHP中四舍五入到五的近似倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文