【问题标题】:How do I round down a decimal to 2 decimal places in .Net?如何在 .Net 中将小数舍入到小数点后 2 位?
【发布时间】:2010-09-26 10:10:36
【问题描述】:

这应该很容易,但是我找不到内置方法,.net框架必须有方法才能做到这一点!

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;
}

【问题讨论】:

  • 您要舍入小数本身还是文本表示?
  • @Henk,我需要将值输出为文本,但宁愿在输出之前进行舍入。很可能该值稍后必须输入到其他计算中。
  • 你真的接受你自己的帖子作为答案,而它甚至没有代码吗?大声笑
  • @codemonkeyliketab 他似乎非常需要这些点......

标签: .net decimal rounding


【解决方案1】:

如果你是四舍五入向下,那么你需要:

Math.Floor(number * 100) / 100;

如果您正在寻找一种叫做“银行家四舍五入”的东西(如果它是用于输出而不是用于统计/求和,则可能不是)那么:

Math.Round(number, 2);

最后,如果您愿意,不确定正确的术语是什么,“正常舍入”:

Math.Round(number, 2, MidpointRounding.AwayFromZero);

【讨论】:

  • 看看我下面的回复: MidpointRounding.AwayFromZero 或 MidpointRounding.ToEven 指定如何处理以 '5' 结尾的数字:MidpointRounding.ToEven 指定 1.135 应该舍入到 1.13,而 1.145 到 1.15 MidpointRounding.AwayFromZero 指定 1.135 应该舍入到 1.14,以及 1.145 到 1.15
【解决方案2】:

如果您想向下取整,请使用Math.Floor,如果您想要精确取整,请使用Math.Round。 Math.Truncate 只需删除数字的小数部分,因此负数会得到不好的结果:

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

Math.Floor 始终返回小于 (Floor ) 或大于 (Ceiling) 指定值的最小整数值。所以你没有得到正确的四舍五入。示例:

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

总是更喜欢包含中点舍入参数的 Math.Round 版本。此参数指定如何将中点值 (5) 作为最后一位处理。

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

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

改为使用 MidPoint.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】:

    使用.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】:
      Math.Floor(number * 100) / 100;
      

      【讨论】:

      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        • 2018-01-17
        相关资源
        最近更新 更多