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条)

报告相同问题?

悬赏问题

  • ¥20 关于php中URL传递GET全局变量的问题
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件