1

PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number? For example:

num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000
LF00
  • 27,015
  • 29
  • 156
  • 295
nmax
  • 981
  • 1
  • 11
  • 19

4 Answers4

0
function num_to_scale($number) {
  $multiple=1; $test=1;
  for ($i=1; $test>=1; $i++) {
    $factor = $multiple/10;
    $test = $number/$multiple;
    $multiple = $multiple*10;
    $scale = floor($number/$factor)*$factor;
  } return $scale;
}

or more simply:

function num_to_scale($n) {
  $m=1; $t=1;
  for ($i=1; $t>=1; $i++) {
    $f=$m/10; $t=$n/$m; $m=$m*10; $s=floor($n/$f)*$f;
  } return $s;
}

Combined with a helper function to convert integers to text strings, we can easily do something like this:

echo 'Over '.num_to_scale(5395206).' units sold.';
// Over five million units sold.
nmax
  • 981
  • 1
  • 11
  • 19
0

try this:

function num_to_scale($number) {
    $num = (int) floor($number);
    $ln = strlen($num) - 1;

    return (int) floor($num / pow(10, $ln)) * pow(10, $ln);
}
Aboudeh87
  • 716
  • 5
  • 16
0

Try this code, check the live demo. You also can refer to this post.

  $floor = floor($v);
  return str_pad(substr($floor, 0, 1), strlen($floor), '0');
LF00
  • 27,015
  • 29
  • 156
  • 295
0

My answer uses logarithm :

function num_to_scale($var) {
    $nbDigits = (int)log($var,10);
    return (int)($var/10**$nbDigits)*10**$nbDigits;
}
Abrikot
  • 965
  • 1
  • 9
  • 21