代码之家  ›  专栏  ›  技术社区  ›  Ian Ringrose

在.Net中,如何将一个小数位舍入到两个小数位?

  •  9
  • Ian Ringrose  · 技术社区  · 14 年前

    这应该很容易,但我找不到合适的方法 内置方法

    private decimal RoundDownTo2DecimalPlaces(decimal input)
    {
       if (input < 0)
       {
          throw new Exception("not tested with negitive numbers");
       }
    
       // There must be a better way!
       return Math.Truncate(input * 100) / 100;
    }
    
    5 回复  |  直到 14 年前
        1
  •  18
  •   FinnNk    14 年前

    向下 那么你需要:

    Math.Floor(number * 100) / 100;
    

    Math.Round(number, 2);
    

    Math.Round(number, 2, MidpointRounding.AwayFromZero);
    
        2
  •  6
  •   Andrea Parodi    14 年前

    使用 Math.Floor Math.Round

    var result= Math.Floor(number * 100) / 100;
    

    数学。地板始终返回小于指定值(下限)或大于指定值(上限)的最小整数值。所以你得不到正确的舍入。例子:

    Math.Floor(1.127 * 100) / 100 == 1.12 //should be 1.13 for an exact round
    Math.Ceiling(1.121 * 100) / 100 == 1.13 //should be 1.12 for an exact round
    

    如果不将AwayFromZero指定为param的值,则会得到默认行为,即ToEven。 例如,使用ToEven作为舍入方法,可以得到:

    Math.Round(2.025,2)==2.02 
    Math.Round(2.035,2)==2.04
    

    相反,使用中点.AwayFromZero参数:

    Math.Round(2.025,2,MidpointRounding.AwayFromZero)==2.03
    Math.Round(2.035,2,MidpointRounding.AwayFromZero)==2.04
    

    var value=2.346;
    var result = Math.Round(value, 2, MidpointRounding.AwayFromZero);
    
        3
  •  3
  •   Kamran Khan    14 年前

    使用 .Truncate() 得到确切的数量,或者 .Round() 四舍五入。

    decimal dNum = (decimal)165.6598F;
    decimal dTruncated = (decimal)(Math.Truncate((double)dNum*100.0) / 100.0); //Will give 165.65
    decimal dRounded = (decimal)(Math.Round((double)dNum, 2)); //Will give 165.66
    

    或者您可以创建一个扩展方法来像这样运行它 dNum.ToTwoDecimalPlaces();

    public static class Extensions
    { 
        public static decimal ToTwoDecimalPlaces(this decimal dNum)
        {
            return ((decimal)(Math.Truncate((double)dNum*100.0) / 100.0));
        }
    }
    
        4
  •  2
  •   Itay Karo    14 年前
    Math.Floor(number * 100) / 100;
    
        5
  •  0
  •   Ian Ringrose    14 年前

    在.net框架中没有内置的方法可以做到这一点,其他的答案是如何编写自己的代码。