我想要所有这些数字的3000
:
3001 - 3500 - 3999
我想要所有这些号码的40000
:
40000.3 - 40101 - 48000.8 - 49901
我想要所有这些号码的20
:
21 - 25.2 - 29
有两个PHP函数可以使数字舍入(floor和round),但它们都不能完全满足我的需要。
注意:我不知道我的号码包含多少位数。如果事实正在改变。
有什么方法可以做到这一点吗?
实现这一点有"多种"方法。其中之一是:
<?php
echo roundNumber( 29 )."<br>";
echo roundNumber( 590 )."<br>";
echo roundNumber( 3670 )."<br>";
echo roundNumber( 49589 )."<br>";
function roundNumber( $number )
{
$digitCount = floor( log10( $number ) ) ;
$base10 = pow( 10, $digitCount );
return floor( $number / $base10 ) * $base10;
}
?>
输出是这样的:
20
500
3000
40000
这将适用于任何数量的数字。试试这个:
$input = 25.45;
if (strpos($input, ".") !== FALSE) {
$num = explode('.', $input);
$len = strlen($num[0]);
$input = $num[0];
} else {
$len = strlen($input);
}
$nearest_zeroes = str_repeat("0", $len-1);
$nearest_round = '1'.$nearest_zeroes;
echo floor($input/$nearest_round) * $nearest_round;
这个想法是,当你四舍五入一个4位数的no时,比如3999,$nearest_round应该是1000。
对于39990(5位数),$nearest_round=10000。
对于25(2位数),$nearest_round=10。
等等。
因此,我们的想法是根据$input的位数动态生成$nearest_round。
希望这能有所帮助。