【问题标题】:Round a decimal to the nearest quarter in C#在 C# 中将小数四舍五入到最近的四分之一
【发布时间】:2011-02-19 01:19:04
【问题描述】:

c# 中是否有一种简单的方法将小数四舍五入到最接近的四分之一,即 x.0、x.25、x.50 x.75 例如 0.21 将舍入为 0.25,5.03 将舍入为 5.0

提前感谢您的帮助。

【问题讨论】:

    标签: c# decimal rounding


    【解决方案1】:

    基于this answer的扩展方法。

    namespace j
    {
        public static class MathHelpers
        {
            public static decimal RoundToNearestQuarter(this decimal x)
            {
                return Math.Round(x * 4, MidpointRounding.ToEven) / 4;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      或者,您可以使用此博客中给出的 UltimateRoundingFunction: http://rajputyh.blogspot.in/2014/09/the-ultimate-rounding-function.html

      //amountToRound => input amount
      //nearestOf => .25 if round to quater, 0.01 for rounding to 1 cent, 1 for rounding to $1
      //fairness => btween 0 to 0.9999999___.
      //            0 means floor and 0.99999... means ceiling. But for ceiling, I would recommend, Math.Ceiling
      //            0.5 = Standard Rounding function. It will round up the border case. i.e. 1.5 to 2 and not 1.
      //            0.4999999... non-standard rounding function. Where border case is rounded down. i.e. 1.5 to 1 and not 2.
      //            0.75 means first 75% values will be rounded down, rest 25% value will be rounded up.
      decimal UltimateRoundingFunction(decimal amountToRound, decimal nearstOf, decimal fairness)
      {
          return Math.Floor(amountToRound / nearstOf + fairness) * nearstOf;
      }
      

      在下面调用标准四舍五入。即 1.125 将四舍五入为 1.25

      UltimateRoundingFunction(amountToRound, 0.25m, 0.5m);
      

      调用下面的四舍五入边框值。即 1.125 将四舍五入为 1.00

      UltimateRoundingFunction(amountToRound, 0.25m, 0.4999999999999999m);
      

      UltimateRoundingFunction 无法实现所谓的“银行家的四舍五入”,您必须使用 paxdiablo 的答案以获得该支持:)

      【讨论】:

      • 这正是我需要四舍五入到最近的 n。
      【解决方案3】:

      将它乘以四,round 它根据需要得到一个整数,然后再除以四:

      x = Math.Round (x * 4, MidpointRounding.ToEven) / 4;
      

      可以在这个出色的答案here 中找到各种舍入选项及其解释:-)

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多