【问题标题】:Round to multiple of a number四舍五入为数的倍数
【发布时间】:2013-08-22 05:57:24
【问题描述】:

我正在尝试创建一个函数,将数字四舍五入为给定数字的最接近的整数倍。

所以如果数字是 15 我们有

  • 14,4 轮到 15
  • -14,4 轮到 -15
  • 14,5 轮到 15
  • 28 轮到 30 轮
  • -28 轮到 -30

等等。我已经编写了一些代码,但似乎无法按预期工作:

public static int RoundToFactor(float number, float Factor)
{
        int returnNumber;

        if((number%Factor) == 0) {
            returnNumber = (int)number;
        }

        returnNumber = (int) (Mathf.Round(number/Factor)*Factor);

        return returnNumber;
}

【问题讨论】:

标签: c# math rounding


【解决方案1】:

这是我做的一个方法。它应该适合您的需求。我添加了一个额外的参数,要求在它同样接近时向上或向下舍入。 (另外,如果您注意到数字在负数时看起来像错误,例如 199 四舍五入到最接近的 2 舍入因子,如有必要,向上是 200。将 199 更改为 -199,结果变为 -198,这不是一个错误,它只是简单地四舍五入。)

public static double RoundToFactor(double Number, int Factor, bool RoundDirection = true)
    {/*round direction: in the event that the distance is 
      * equal from both next factors round up (true) down (false)*/

        double multiplyBy;
        if ((Number % Factor).Equals(0f))
        {
            return Number;
        }
        else
        {
            multiplyBy = Math.Round(Number / Factor);
            int Low = (int)multiplyBy - 1;
            int Mid = (int)multiplyBy;
            int High = (int)multiplyBy + 1;

            List<double> li = new List<double>() { Low, Mid, High };
            double minDelta = double.MaxValue;
            double Closest = 0d;

            foreach (double dbl in li)
            {
                double db = dbl * Factor;
                double Delta = (db < Number) ? (Number - db) : (db - Number);
                if (RoundDirection ? Delta <= minDelta : Delta < minDelta)
                {
                    minDelta = Delta;
                    Closest = db;
                }
            }
            return Closest;

        }

        throw new Exception("Math has broken!!!");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-26
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多