简体   繁体   English

如何进行数字回合?

[英]How to make a digit round?

I want 3000 for all these numbers: 我希望所有这些数字为3000

3001 - 3500 - 3999

I want 40000 for all these numbers: 我希望所有这些数字为40000

40000.3 - 40101 - 48000.8 - 49901

I want 20 for all these numbers: 这些数字我要20

21 - 25.2 - 29

There is two PHP function to make a digit round ( floor and round ) But none of them don't act exactly what I need . 有两个PHP功能,使一个数字圆 ),但都没有他们不正是我需要的行动

Note: I don't know my number is contains how many digits. 注意:我不知道我的电话号码包含多少位数字。 If fact it is changing. 如果事实正在改变。

Is there any approach to do that? 有没有办法做到这一点?

There are "many" ways how to achieve this. 有很多方法可以实现这一目标。 One is this: 一个是这样的:

<?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;
}
?>

The output is this: 输出是这样的:

20
500
3000
40000

This will work for any no. 这将适用于任何否。 of digits. 的数字。 Try this: 尝试这个:

$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;

The idea is when you round a 4 digit no, say 3999, $nearest_round should be 1000. 这个想法是,当您四舍五入一个4位数字,例如3999时,$ nearest_round应该为1000。

For 39990(5 digit), $nearest_round = 10000. 对于39990(5位数字),$ nearest_round = 10000。

For 25(2 digit), $nearest_round = 10. 对于25(2位数),$ nearest_round = 10。

And so on. 等等。

So, the idea is to generate $nearest_round dynamically based on the no. 因此,该想法是基于no动态生成$ nearest_round。 of digits of $input. $ input的位数。

Hope this helps. 希望这可以帮助。

PHP allows negative precision for round such as with: round(3993,-3); PHP允许舍入为负精度,例如: round(3993,-3);

Output: 3000 产量: 3000

n    round(1111.1111,n)
==   ==================
 3   1111.111
 2   1111.11
 1   1111.1
 0   1111
-1   1110
-2   1100
-3   1000

W3S about round W3S关于轮

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

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