Round to max thousand, hundred etc in PHP

Viewed 2472

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!

5 Answers

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

Related