首页 > 解决方案 > 如何根据以下条件对数字进行四舍五入

问题描述

我想根据以下数字对任何数字进行四舍五入。数字如下。认为,

case 1) I have number 0.1 Between 0.24, then the round output should be 0.25
case 2) number 0.26 Between 0.49, then the round output should be 0.50
case 3) number 0.51 Between 0.74, then the round output should be 0.75
case 4) number 0.76 Between 0.99, then the round output should be 1.00

case 5) I have number 1.1 Between 1.24, then the round output should be 1.25
case 6) number 1.26 Between 1.49, then the round output should be 1.50
case 7) number 1.51 Between 1.74, then the round output should be 1.75
case 8) number 1.76 Between 1.99, then the round output should be 2.00

这里的数字是动态的。并且数字将始终大于零。

请帮助我并提出如何可能的建议。

标签: php

解决方案


看起来像(美国)钱。看起来像“四舍五入到最近的四分之一”。

注意图案。在每种情况下,它都应该添加一些数字以获得最近的四分之一。您需要做的就是计算要添加多少。

您可能熟悉模运算符和“技术”描述

$a % $b     Modulo  Remainder of $a divided by $b.

但请记住,“余数”还告诉除数 ($b) 和被除数的倍数 ($a) 之间的“距离”。

一个简单的例子:27 % 25 = 2. 27 比 25 的倍数多 2。它也25 - 2 = 23小于 25 的下一个倍数。那么,四舍五入,等式将是27 + (25 - (27 % 25))

但唉,%只适用于整数。您需要使用该fmod函数对浮点数进行操作。

(警告:没有一个例子是 0.25 的倍数。这些输入必须用异常情况处理,以防止添加额外的 0.25)。


推荐阅读