Round to max thousand, hundred etc in PHP

前端 未结 5 447
庸人自扰
庸人自扰 2020-11-30 14:24

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

相关标签:
5条回答
  • 2020-11-30 15:05

    Really not impressed by everyone using string operations!

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

    https://www.tehplayground.com/Vihmm7bqHtYDohRo

    0 讨论(0)
  • 2020-11-30 15:12

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 15:16
    <?php
    $value = 14;
    $len = strlen($value);
    $div = str_pad('1', $len, "0");
    echo ceil($value / $div) * $div;
    ?>
    
    0 讨论(0)
  • 2020-11-30 15:23

    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);
    }
    
    0 讨论(0)
  • 2020-11-30 15:31

    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;
    ?>
    
    0 讨论(0)
提交回复
热议问题