duanjiao5082 2015-08-03 09:40
浏览 60
已采纳

使用未知数字进行Round Down

I have a table with a decimal field, which I need to round down.

Here's a data snippet of the table:

number
9.5
9.53
7.25
6.9
9.6
8.0
8.3
8.75
9.0
12.25
12.65
11.0

If a number is between XXX.0 and XXX.5 the number needs to round down to XXX.0 (eg. 8.3 or 12.25 expecting 8.0 or 12.0)

If the number is between XXX.5 and XXX.0 the number needs to round down to XXX.5 (eg. 9.53 or 9.6 expecting 9.5 or 9.5)

Else the number should stay unchanged (eg. 8.0 or 11.0)

Here is my question: How can I define what is in front of the decimal, this can be anything between 0 and 20? I have not found anything similar anywhere... Is there a way to only look at the value after the decimal?

Here is a sample code snipped, where XXX is the unknown part of the decimal number:

if(($number > XXX.0) && ($number < XXX.5))
    { $newNumber = round($number, 0, PHP_ROUND_HALF_DOWN); }

elseif(($number > XXX.5) && ($number < XXX.0))
    { $newNumber = round($number, 0, PHP_ROUND_HALF_DOWN); }

elseif(($number == XXX.5) || ($number == XXX.0))
    { $newNumber = $number; }
  • 写回答

4条回答 默认 最新

  • dsaff82024 2015-08-03 12:03
    关注

    You can use fmod to return the floating point remainder, then do a simple ternary to output your desired result.

    <?php
    
    $n = array(
    8.3, //8.0
    12.25, //12.00
    9.53, //9.5
    9.6 //9.5
    );
    
    foreach($n as $i) {
       echo $i .' = '. (fmod($i, 1) > 0.5 
               ? sprintf("%2.f", (float) (int) $i + 0.5) 
               : sprintf("%2.f", (float) (int) $i)) . PHP_EOL; 
    }
    

    https://eval.in/411076

    And in function form;

    function round_mid($i) {
       return (fmod($i, 1) > 0.5 
                 ? sprintf("%2.f", (float) (int) $i + 0.5) 
                 : sprintf("%2.f", (float) (int) $i));
    }
    

    https://eval.in/411080

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP