1

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?

stack
  • 10,280
  • 19
  • 65
  • 117
  • 1
    Easiest way in my mind, count the strlen (string length), and then take the first number and ensure via the string length count, that it gets the correct amount of 0's. – Anees Saban Apr 10 '16 at 13:39

2 Answers2

3

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
Peter VARGA
  • 4,780
  • 3
  • 39
  • 75
1

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.

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32