PHP中根据分数四舍五入十进制数 [英] Round up decimal number according to fraction in PHP

查看:67
本文介绍了PHP中根据分数四舍五入十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将 excel 公式转换为 php 函数.现在我面临一个作为分数四舍五入的问题.请让我解释一下:

I am working to convert an excel formula to php function. Now I am facing a problem that is round up as the fraction. Please let me explain it:

  • (2 * 18)/2.98 = 12.08 但根据我的要求应该是 12.25
    • (2 * 18.5)/2.98 = 12.416 但根据我的要求应该是 12.50
    • (2 * 18.8)/2.98 = 12.617 但根据我的要求应该是 12.75

    在excel中,它是这样做的:

    In excel, it is done like :

    • 天花板(( 2 * 18 )/2.98, 0.25) = 12.25
      • 天花板(( 2 * 18.5 )/2.98, 0.25) = 12.50
      • 天花板(( 2 * 18.8 )/2.98, 0.25) = 12.75

      我在 PHP 中尝试过.Ceil() 和 Floor() 没有达到目的,因为这两个将相应地给出输出 13 和 12.

      I tried in PHP. Ceil() and Floor() do not serve the purpose as these 2 shall give output 13 and 12 accordingly.

      另一轮() 使用了这些选项PHP_ROUND_HALF_UP、PHP_ROUND_HALF_DOWN、PHP_ROUND_HALF_EVEN 或 PHP_ROUND_HALF_ODD,这些选项没有达到目的.

      Another one round() uses these options PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD which does not serve the purpose.

      有人帮我吗?

      推荐答案

      使用这个功能:

      function fractionRound($num,$frac) {
        return ceil($num/$frac)*$frac;
      }
      

      这样称呼:

      echo fractionRound(( 2 * 18 )/2.98, 0.25); 
      

      它将四舍五入到最接近的 0.25 它将返回 12.25

      it will round to the nearest 0.25 it will return 12.25

      这篇关于PHP中根据分数四舍五入十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆