用0和5舍入该值

  • I want to round up the value with 0 or 5 based on the below conditions. For example:

    160.1 to 162.5  ---> 160 (value expected)
    162.6 to 167.5  ---> 165 (value expected) 
    167.6 to 169.9  ---> 170 (value expected)
    
  • Below is my code which i tried with a scenario:


$main_value=3831.25;
if(is_int($main_value))
{
$main_value=number_format($main_value,1);
}

$arr = explode(".", $main_value);
$firstvalue=substr($arr['0'],-1);
$secoundvalue=substr($arr['1'],0,1);
//echo "<pr>";print_r($firstvalue.$secoundvalue);exit;
$default=$firstvalue.$secoundvalue;
//echo "<pr>";print_r($default);exit;
if($default>=1 && $default<=25){
  echo   $output=$main_value-($default/10);
}elseif ($default>25 && $default<=50) {
  $temp_val=50-$default;
  echo $output=$main_value+($temp_val/10);
}elseif($default>50  && $default<=75){
  $temp_val=$default-50;
  echo $output=$main_value-($temp_val/10);
}else{
  $temp_val=100-$default;
  echo $output=$main_value+($temp_val/10);
}
  • But the output i coming as 3830.05. Is there any other way to get the expected output.

You can take advantage of the built-in round() function.

You can do that by dividing by 5, using round() and multiplying by 5 again. Note that you need to round the numbers in the middle down to meet your requirements:

$rounded = round($number / 5, 0, PHP_ROUND_HALF_DOWN) * 5;

An example.

Edit: In javascript there is no PHP_ROUND_HALF_DOWN parameter and all values in the middle are rounded up. To get the same result, you can round the negative version of the number - which will be rounded up, towards 0 - and take the negative of that again:

var rounded = -Math.round(-number / 5) * 5;