【问题标题】:How to round up or down in C#?如何在 C# 中向上或向下舍入?
【发布时间】:2019-10-22 15:21:18
【问题描述】:

我尝试过使用 Math.Round 和 MidpointRounding。这似乎不能满足我的需要。

例子:

52.34567 rounded to 2 decimals UP   = 52.35  
 1.183   rounded to 2 decimals DOWN =  1.18

我需要编写自定义函数吗?

编辑:

我应该更具体的。

有时我需要一个像 23.567 这样的数字来向下舍入到 23.56。 在这种情况下...

Math.Round(dec, 2, MidpointRounding.AwayFromZero) gives 23.57
Math.Round(dec, 2, MidpointRounding.ToEven) gives 23.57

最多可以输出小数点后 9 位的小数,需要四舍五入到小数点后 1、2、3 甚至 4 位。

【问题讨论】:

  • 您是否尝试过乘以 100、四舍五入并除以 100?
  • 你能显示你用来进行四舍五入的代码吗?
  • 这似乎对我有用。也许我误解了这个问题? Response.Write(Math.Round(52.34567, 2).ToString()); 输出:52.35
  • 显然他没有尝试过,因为它完全符合他的需要。他甚至可以自己测试:Console.WriteLine(Math.Round(52.34567, 2));Console.WriteLine(Math.Round(1.183, 2));

标签: c# math


【解决方案1】:

尝试使用 decimal.Round():

decimal.Round(x, 2)

x 是您的值,2 是您希望保留的小数位数。

您还可以通过传递第三个参数来指定 .5 是向上还是向下舍入:

decimal.Round(x, 2, MidpointRounding.AwayFromZero);

编辑:

根据新要求(即,尽管数字大于下一个区间的“中途”,但有时会向下舍入),您可以尝试:

var pow = Math.Pow(10, numDigits);
var truncated = Math.Truncate(x*pow) / pow;

Truncate() 去掉小数的非整数部分。注意上面的numDigits应该是你要KEEP的位数,而不是小数的总数等。

最后,如果你想强制向上舍入(截断实际上是强制向下舍入),你只需在再次除之前将 Truncate() 调用的结果加 1。

【讨论】:

    【解决方案2】:

    尝试使用Math.Ceiling(上)或Math.Floor(下)。例如Math.Floor(1.8) == 1.

    【讨论】:

    • 这些功能很好,但是,它们将值强制为整数。在很多情况下我需要保持小数。
    • 如果您想使用小数,您可以这样做:Math.Floor(1.87*10)/10 == 1.8
    【解决方案3】:

    假设您对号码使用 decimal 类型,

    static class Rounding
    {
        public static decimal RoundUp(decimal number, int places)
        {
            decimal factor = RoundFactor(places);
            number *= factor;
            number = Math.Ceiling(number);
            number /= factor;
            return number;
        }
    
        public static decimal RoundDown(decimal number, int places)
        {
            decimal factor = RoundFactor(places);
            number *= factor;
            number = Math.Floor(number);
            number /= factor;
            return number;
        }
    
        internal static decimal RoundFactor(int places)
        {
            decimal factor = 1m;
    
            if (places < 0)
            {
                places = -places;
                for (int i = 0; i < places; i++)
                    factor /= 10m;
            }
    
            else
            {
                for (int i = 0; i < places; i++)
                    factor *= 10m;
            }
    
            return factor;
        }
    }
    

    例子:

    Rounding.RoundDown(23.567, 2) prints 23.56
    

    【讨论】:

    • 您还可以轻松修改此示例以制作小数类型的扩展方法,例如public static decimal RoundDown(这个十进制数,整数位)
    【解决方案4】:

    对于已接受答案的较短版本,以下是可以使用的 RoundUpRoundDown 函数:

    public double RoundDown(double number, int decimalPlaces)
    {
        return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
    }
    
    public double RoundUp(double number, int decimalPlaces)
    {
        return Math.Ceiling(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
    }
    

    【讨论】:

      【解决方案5】:

      带有结果的完整代码。

        double a = Math.Round(128.5, 0, MidpointRounding.AwayFromZero);
      

      结果是 129

      【讨论】:

        【解决方案6】:

        Math 类为您提供了用于向上和向下舍入的方法,它们分别是 Math.Ceiling()Math.Floor()。它们像Math.Round() 一样工作,但它们有一个特殊性,它们只接收一个值并将它们四舍五入到整个部分。

        因此,您需要使用Math.Pow() 将该值乘以 10 到您需要四舍五入的 n 小单位,然后您需要除以相同的乘积值。

        请注意,Math.Pow() 方法的输入参数是double,因此需要将它们转换为double

        例如:

        当你想将值四舍五入到小数点后3位(假设值类型为decimal):

        double decimalsNumber = 3;
        decimal valueToRound = 1.1835675M;
        // powerOfTen must be equal to 10^3 or 1000.
        double powerOfTen = Math.Pow(10, decimalsNumber);
        // rounded must be equal to Math.Ceiling(1.1835675 * 1000) / 1000
        decimal rounded = Math.Ceiling(valueToRound * (decimal)powerOfTen) / (decimal)powerOfTen;
        
        
        Result: rounded = 1.184
        

        当你想将值四舍五入到小数点后3位(假设值类型为decimal):

        double decimalsNumber = 3;
        decimal valueToRound = 1.1835675M;
        // powerOfTen must be equal to 10^3 or 1000.
        double powerOfTen = Math.Pow(10, decimalsNumber);
        // rounded must be equal to Math.Floor(1.1835675 * 1000) / 1000
        decimal rounded = Math.Floor(valueToRound * (decimal)powerOfTen) / (decimal)powerOfTen;
        
        
        Result: rounded = 1.183
        

        要参考如何更具体地使用它们并获取更多信息以及这两种方法,您可以从官方 MSDN Microsoft 站点查看这些页面:

        Math Class

        Math.Pow Method (Double, Double)

        Math.Floor Method (Decimal)

        Math.Floor Method (Double)

        Math.Ceiling Method (Decimal)

        Math.Ceiling Method (Double)

        【讨论】:

          【解决方案7】:

          试试这个自定义舍入

          public int Round(double value)
          {
              double decimalpoints = Math.Abs(value - Math.Floor(value));
              if (decimalpoints > 0.5)
                  return (int)Math.Round(value);
              else
                  return (int)Math.Floor(value);
          }
          

          【讨论】:

            【解决方案8】:

            也许是这个?

            Math.Round(dec + 0.5m, MidpointRounding.AwayFromZero);
            

            【讨论】:

              【解决方案9】:

              您可以通过使用 Math.Round() 或 decimal.Round()- 的方法来实现:

              Math.Round(amt)
              Math.Round(amt, Int32) and other overloading methods.
              
              
              decimal.Round(amt)
              decimal.Round(amt, 2) and other overloding methods.
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2012-02-05
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多