doukang1962 2016-09-10 08:23
浏览 32
已采纳

用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.
  • 写回答

1条回答 默认 最新

  • dousi6303 2016-09-10 08:35
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题