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 :
etc etc
I would like to create an automatic function to do that, according to the value passed.
Thanks!
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;
}
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;
?>
<?php
$value = 14;
$len = strlen($value);
$div = str_pad('1', $len, "0");
echo ceil($value / $div) * $div;
?>
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);
}
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;