3

I have a pretty simple PHP question but I'm not sure how to do that.

I want to round to the max hundred or thousand depending on the value returned by the database.

Here are a few examples of what I need :

  • DB returns the value 11, I want PHP to output 20
  • DB returns the value 104, I want PHP to output 200
  • DB returns the value 1404, I want PHP to output 2000
  • DB returns the value 10241, I want PHP to output 11000

etc etc

I would like to create an automatic function to do that, according to the value passed.

Thanks!

LF00
  • 27,015
  • 29
  • 156
  • 295
fraxool
  • 3,199
  • 4
  • 31
  • 57

5 Answers5

6

Final implementation, inspired from Shaunkak's answer and SO's comment. Thanks for these bra..s. live demo

<?php
  $val = 10241.67;
  if($val >= 1000) {
    echo ceil($val / 1000) * 1000;
  }
  else {
    $length = strlen(ceil($val));
    $times = str_pad('1', $length, "0");
    echo ceil($val / $times) * $times;
}
Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295
5

Really not impressed by everyone using string operations!

$zeros = floor(log($value) * log10(M_E));
$zeros = min($zeros, 3); // Only round to tens, hundreds or thousands
$tens = pow(10, $zeros);
$result = ceil($value / $tens) * $tens;

https://www.tehplayground.com/kipIy3CPymY1TZsf

Hamish
  • 2,763
  • 1
  • 17
  • 21
2
<?php
$value = 14;
$len = strlen($value);
$div = str_pad('1', $len, "0");
echo ceil($value / $div) * $div;
?>
Shaunak Shukla
  • 2,347
  • 2
  • 18
  • 29
1

Try this one

<?php
    $input = 10241; //this will be your input
    $charLength = strlen($input);
    $number = [1,10,100,1000,10000,100000];
    $output = ceil($input / $number[$charLength - 1]) * $number[$charLength - 1]; //same like this ceil($input / 10) * 10;
?>
Casper
  • 1,469
  • 10
  • 19
1

Here is my 2 cents:

$v = 11;

if(strlen($v)<4) { 
    $v = str_pad((int)(substr($v, 0, 1)+1), strlen($v), 0, STR_PAD_RIGHT);
} else {
    $v = substr($v, 0, -4) . str_pad((int)(substr($v, -4, -3)+1), 4, 0, STR_PAD_RIGHT);
}
hatef
  • 5,491
  • 30
  • 43
  • 46