【问题标题】:How do you round a number to two decimal places in C#?如何在 C# 中将数字四舍五入到小数点后两位?
【发布时间】:2010-09-20 09:32:13
【问题描述】:

我想使用Math.Round 函数来实现这一点

【问题讨论】:

    标签: c# decimal rounding bankers-rounding


    【解决方案1】:

    这里有一些例子:

    decimal a = 1.994444M;
    
    Math.Round(a, 2); //returns 1.99
    
    decimal b = 1.995555M;
    
    Math.Round(b, 2); //returns 2.00
    

    您可能还想查看以下重载的银行家四舍五入/四舍五入:

    Math.Round(a, 2, MidpointRounding.ToEven);
    

    有更多关于它的信息here

    【讨论】:

    • 您应该澄清 MidPointRounding.ToEven 是默认值。如果你想要 AwayFromZero 你将不得不使用重载
    • 如果您想向上取整到小数点后 2 位,请在四舍五入前将0.005 添加到数字。与向下舍入类似,在传递给Math.Round函数之前减去0.005
    • .NET 默认为MidPointRounding.ToEven(又名“银行家四舍五入”)的原因是因为我们在学校都学会了四舍五入,而 0.5 向上舍入会导致太多舍入。这是处理金钱、税收计算等时的问题。
    【解决方案2】:

    试试这个:

    twoDec = Math.Round(val, 2)
    

    【讨论】:

      【解决方案3】:

      如果你想要一个字符串

      > (1.7289).ToString("#.##")
      "1.73"
      

      或者小数

      > Math.Round((Decimal)x, 2)
      1.73m
      

      但请记住!舍入不是分布式的,即。 round(x*y) != round(x) * round(y)。因此,在计算结束之前不要进行任何舍入,否则会失去准确性。

      【讨论】:

        【解决方案4】:

        就我个人而言,我从不四舍五入。保持它尽可能坚定,因为无论如何四舍五入在CS中有点像红鲱鱼。但是您确实想为您的用户格式化数据,为此,我发现string.Format("{0:0.00}", number) 是一个好方法。

        【讨论】:

        • 这更适合显示目的,尤其是金钱,因为 5.4 英镑(使用 Math.round)看起来不如 5.40 英镑(这样)。
        • 我在 string.Format("0:0.00", number) 之前尝试过,但没有成功。这些方括号非常重要,因此: string.Format("{0:0.00}", number) 有效。
        • @FrenkyB 当你说“方括号”时,我希望你指的是大括号。
        • 这一轮也是。 1.009 => 1.01
        【解决方案5】:

        // 转换为小数点后两位

        String.Format("{0:0.00}", 140.6767554);        // "140.67"
        String.Format("{0:0.00}", 140.1);             // "140.10"
        String.Format("{0:0.00}", 140);              // "140.00"
        
        Double d = 140.6767554;
        Double dc = Math.Round((Double)d, 2);       //  140.67
        
        decimal d = 140.6767554M;
        decimal dc = Math.Round(d, 2);             //  140.67
        

        =========

        // just two decimal places
        String.Format("{0:0.##}", 123.4567);      // "123.46"
        String.Format("{0:0.##}", 123.4);         // "123.4"
        String.Format("{0:0.##}", 123.0);         // "123"
        

        还可以将“0”与“#”组合。

        String.Format("{0:0.0#}", 123.4567)       // "123.46"
        String.Format("{0:0.0#}", 123.4)          // "123.4"
        String.Format("{0:0.0#}", 123.0)          // "123.0"
        

        【讨论】:

        • String.Format("{0:0.00}", 140.6767554); != "140.67" 它实际上呈现为 "140.68" - 向上取整
        【解决方案6】:

        Wikipedia has a nice page 关于四舍五入。

        所有 .NET(托管)语言都可以使用任何公共语言运行时(CLR)的舍入机制。例如,Math.Round()(如上所述)方法允许开发人员指定舍入类型(舍入到偶数或远离零)。 Convert.ToInt32() 方法及其变体使用round-to-evenCeiling()Floor() 方法是相关的。

        您也可以使用custom numeric formatting 进行四舍五入。

        请注意,Decimal.Round() 使用与 Math.Round() 不同的方法;

        这是银行家舍入算法的useful post。 看看 Raymond 的幽默posts here 之一关于四舍五入...

        【讨论】:

          【解决方案7】:

          这是为了在 C# 中舍入到小数点后 2 位:

          label8.Text = valor_cuota .ToString("N2") ;
          

          在 VB.NET 中:

           Imports System.Math
           round(label8.text,2)
          

          【讨论】:

            【解决方案8】:

            如果你想对一个数字进行四舍五入,你可以获得不同的结果,具体取决于:你如何使用 Math.Round() 函数(如果是向上舍入或向下舍入),你正在使用双打和/或浮点数,然后应用中点舍入。特别是,当使用其中的操作或要舍入的变量来自操作时。假设您想将这两个数字相乘:0.75 * 0.95 = 0.7125。正确的?不在 C# 中

            让我们看看如果你想四舍五入到小数点后第三位会发生什么:

            double result = 0.75d * 0.95d; // result = 0.71249999999999991
            double result = 0.75f * 0.95f; // result = 0.71249997615814209
            
            result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
            result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713
            

            如您所见,如果您想向下舍入中点,第一个 Round() 是正确的。但是第二个 Round() 如果要四舍五入就错了。

            这适用于负数:

            double result = -0.75 * 0.95;  //result = -0.71249999999999991
            result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
            result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713
            

            所以,恕我直言,您应该为 Math.Round() 创建自己的包装函数,以满足您的要求。我创建了一个函数,其中参数“roundUp=true”表示舍入到下一个更大的数字。即:0.7125 舍入为 0.713,-0.7125 舍入为 -0.712(因为 -0.712 > -0.713)。这是我创建的函数,适用于任意数量的小数:

            double Redondea(double value, int precision, bool roundUp = true)
            {
                if ((decimal)value == 0.0m)
                    return 0.0;
            
                double corrector = 1 / Math.Pow(10, precision + 2);
            
                if ((decimal)value < 0.0m)
                {
                    if (roundUp)
                        return Math.Round(value, precision, MidpointRounding.ToEven);
                    else
                        return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
                }
                else
                {
                    if (roundUp)
                        return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
                    else
                        return Math.Round(value, precision, MidpointRounding.ToEven);
                }
            }
            

            变量 'corrector' 用于修复浮点数或双精度数运算的不准确性。

            【讨论】:

              【解决方案9】:

              我知道这是一个老问题,但请注意数学轮次字符串格式轮次之间的以下区别:

              decimal d1 = (decimal)1.125;
              Math.Round(d1, 2).Dump();   // returns 1.12
              d1.ToString("#.##").Dump(); // returns "1.13"
              
              decimal d2 = (decimal)1.1251;
              Math.Round(d2, 2).Dump();   // returns 1.13
              d2.ToString("#.##").Dump(); // returns "1.13"
              

              【讨论】:

                【解决方案10】:

                您可能要检查的一件事是 Math.Round 的舍入机制:

                http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

                除此之外,我推荐 Math.Round(inputNumer, numberOfPlaces) 方法而不是 *100/100 方法,因为它更干净。

                【讨论】:

                  【解决方案11】:

                  有一个奇怪的情况,我有一个十进制变量,当序列化 55.50 时,它总是在数学上将默认值设置为 55.5。但是,由于某种原因,我们的客户端系统严重期望 55.50,他们肯定期望十进制。那是我编写以下帮助程序的时候,它总是将任何十进制值转换为用零填充的 2 位数字,而不是发送一个字符串。

                  public static class DecimalExtensions
                  {
                      public static decimal WithTwoDecimalPoints(this decimal val)
                      {
                          return decimal.Parse(val.ToString("0.00"));
                      }
                  }
                  

                  用法应该是

                  var sampleDecimalValueV1 = 2.5m;
                  Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());
                  
                  decimal sampleDecimalValueV1 = 2;
                  Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());
                  

                  输出:

                  2.50
                  2.00
                  

                  【讨论】:

                    【解决方案12】:

                    您应该能够使用 Math.Round(YourNumber, 2) 指定要四舍五入的位数

                    您可以阅读更多here

                    【讨论】:

                      【解决方案13】:

                      Math.Floor(123456.646 * 100) / 100 将返回 123456.64

                      【讨论】:

                        【解决方案14】:

                        字符串 a = "10.65678";

                        十进制 d = Math.Round(Convert.ToDouble(a.ToString()),2)

                        【讨论】:

                          【解决方案15】:
                            public double RoundDown(double number, int decimalPlaces)
                                  {
                                      return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
                                  }
                          

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2017-03-26
                            • 2014-03-02
                            • 1970-01-01
                            • 1970-01-01
                            • 2022-01-02
                            相关资源
                            最近更新 更多