【问题标题】:Rounding to nearest truncated 100 [duplicate]四舍五入到最接近的截断 100 [重复]
【发布时间】:2013-06-11 21:55:40
【问题描述】:

我想知道当一个值被截断时如何四舍五入到最接近的 100。 我正在使用这个:

private static int CalculatePaperLevel(int paperLevel)
{
   int roundedLevel = 0;
   roundedLevel = ((int)Math.Round(paperLevel / 10.0) * 10);
   return roundedLevel;
}

但这就是我想要的

例如 191 -> 100

224 -> 200

140 -> 100

295 -> 200

【问题讨论】:

标签: c#


【解决方案1】:

你可以这样做roundedLevel = (paperLevel / 100) * 100;

这是有效的,因为整数运算总是将结果截断为整数。所以

  • (295 / 100) -> 2
  • 2 * 100 -> 200

【讨论】:

    【解决方案2】:

    这样的截断是在 C# 中将两个 ints 相除时发生的。这段代码做你想做的事:

    private static int CalculatePaperLevel(int paperLevel)
    {
       int roundedLevel = paperLevel / 100 * 100;
       return roundedLevel;
    }
    

    【讨论】:

    • 谢谢。我不太确定“截断”到底是什么,这更有意义
    【解决方案3】:

    我相信你想要的函数叫做Math.Floor

    【讨论】:

      【解决方案4】:

      只需使用Math.Floor (37D/100)*100

      【讨论】:

      • 参数37/100 的类型为int。为什么要在 int 上使用 floor 函数?
      • @Jeppe 因为Floor只接受十进制和双精度,所以会被当作十进制处理
      • 除法将返回一个int,因为重载可以描述为int operator /(int, int)(由C#规范定义,不一定是真正的.NET方法)显然是/这里的最佳重载.那么Floor 的重载使用将很难选择。这能编译吗? 编辑:啊,你改了。
      猜你喜欢
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      相关资源
      最近更新 更多