I want 3000
for all these numbers:
3001 - 3500 - 3999
I want 40000
for all these numbers:
40000.3 - 40101 - 48000.8 - 49901
I want 20
for all these numbers:
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.
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.
For 39990(5 digit), $nearest_round = 10000.
For 25(2 digit), $nearest_round = 10.
And so on.
So, the idea is to generate $nearest_round dynamically based on the no. of digits of $input.
Hope this helps.
PHP allows negative precision for round such as with: round(3993,-3);
Output: 3000
n round(1111.1111,n)
== ==================
3 1111.111
2 1111.11
1 1111.1
0 1111
-1 1110
-2 1100
-3 1000