题
我们如何在php中将数字四舍五入到最接近的10?
说我有 23
,我会使用什么代码将其四舍五入到 30
?
解决方案
floor()
将会失效。
ceil()
会上升。
round()
默认情况下最接近。
除以10,执行ceil,然后乘以10以减少有效数字。
$number = ceil($input / 10) * 10;
编辑:我这么久已经这么做了......但是TallGreenTree的答案更清晰。
其他提示
round($number, -1);
这会将$ number舍入到最接近的10.如果需要,您还可以传递第三个变量来更改舍入模式。
我实际上正在搜索可以舍入到最近的变量的函数,并且此页面一直在我的搜索中出现。所以当我最终自己编写这个函数时,我想我会在这里发布它以供其他人查找。
该函数将舍入到最近的变量:
function roundToTheNearestAnything($value, $roundTo)
{
$mod = $value%$roundTo;
return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}
此代码:
echo roundToTheNearestAnything(1234, 10).'<br>';
echo roundToTheNearestAnything(1234, 5).'<br>';
echo roundToTheNearestAnything(1234, 15).'<br>';
echo roundToTheNearestAnything(1234, 167).'<br>';
将输出:
1230
1235
1230
1169
这个问题有很多答案,可能所有人都会给你你想要的答案。但正如@TallGreenTree所提到的那样,它有一个功能。
但@TallGreenTree答案的问题是它没有向上舍入,它会向最接近的10舍入。要解决这个问题,请在您的号码中添加 +5
以便向上舍入。如果要向下舍入,请执行 -5
。
所以在代码中:
round($num + 5, -1);
您不能使用 round模式
进行舍入,因为它只会舍入分数而不是整数。
如果你要四舍五入到最近的 100
,你应该使用 +50
。
div乘以10然后使用ceil然后使用10乘以
尝试
round(23,-1);
我们可以“欺骗”通过回合
$rounded = round($roundee / 10) * 10;
我们也可以避免使用
进行浮点除法function roundToTen($roundee)
{
$r = $roundee % 10;
return ($r <= 5) : $roundee - $r : $roundee + (10 - $r);
}
编辑:我不知道(并且在网站上没有详细记录) round
现在支持“否定”精确,所以你可以更容易使用
$round = round($roundee, -1);
再次编辑:如果您想要整理,可以尝试
function roundUpToTen($roundee)
{
$r = $roundee % 10;
if ($r == 0)
return $roundee;
return $roundee + 10 - $r;
}
$value = 23;
$rounded_value = $value - ($value % 10 - 10);
//$rounded_value is now 30
试试这个:
ceil($roundee / 10) * 10;
向下舍入到最接近的10,然后加10。
round($num, -1) + 10
我的第一个冲动是google for“php math”我发现有一个核心数学库函数叫做“round()”这可能是你想要的。
对于想要使用原始SQL进行操作的人,不使用php,java,python等。
SET SQL_SAFE_UPDATES = 0;
UPDATE db.table SET value = ceil(value / 10)* 10其中value不像'%0';
我想要向上舍入到最大数字位置的下一个数字(是否有名称?),所以我做了以下函数(在php中):
//Get the max value to use in a graph scale axis,
//given the max value in the graph
function getMaxScale($maxVal) {
$maxInt = ceil($maxVal);
$numDigits = strlen((string)$maxInt)-1; //this makes 2150->3000 instead of 10000
$dividend = pow(10,$numDigits);
$maxScale= ceil($maxInt/ $dividend) * $dividend;
return $maxScale;
}
Hey i modify Kenny answer and custom it not always round function now it can be ceil and floor function
function roundToTheNearestAnything($value, $roundTo,$type='round')
{
$mod = $value%$roundTo;
if($type=='round'){
return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}elseif($type=='floor'){
return $value+($mod<($roundTo/2)?-$mod:-$mod);
}elseif($type=='ceil'){
return $value+($mod<($roundTo/2)?$roundTo-$mod:$roundTo-$mod);
}
}
echo roundToTheNearestAnything(1872,25,'floor'); // 1850<br>
echo roundToTheNearestAnything(1872,25,'ceil'); // 1875<br>
echo roundToTheNearestAnything(1872,25,'round'); // 1875
这可以使用PHP的“ fmod ”功能轻松完成。以下代码特定于10,但您可以将其更改为任意数字。
$num=97;
$r=fmod($num,10);
$r=10-$r;
$r=$num+$r;
return $r;
输出:100
试试这个......传递数字要四舍五入,它会四舍五入到最近的第十个。它会帮助....
round($ num,1);