【问题标题】:Decimal/double to integer - round up (not just to nearest)十进制/双精度整数 - 向上舍入(不仅仅是最接近的)
【发布时间】:2011-12-29 09:35:29
【问题描述】:

您如何四舍五入小数或浮点数。比如……

0.0 => 0
0.1 => 1
1.1 => 2
1.7 => 2
2.1 => 3

等等

【问题讨论】:

  • 你希望负数有什么行为? -1.1 会变为 -1(变大)还是 -2(远离零)?

标签: c# numbers


【解决方案1】:

简单,使用Math.Ceiling

var wholeNumber = (int)Math.Ceiling(fractionalNumber);

【讨论】:

  • 我知道这是题外话,但我可以问你为什么使用var 而不是int
  • 完全出于习惯。 var 在声明较长类型的对象时很有用,例如 var myDictionary = new Dictionary<int, List<string>>()
【解决方案2】:

这样的?

int myInt = (int)Math.Ceiling(myDecimal);

【讨论】:

  • 为什么转换成字符串只是为了解析回来?就投吧。
【解决方案3】:

Math.Ceiling 不适合我,我使用这个代码和这个工作 :)

int MyRoundedNumber= (int) MyDecimalNumber;
                if (Convert.ToInt32(MyDecimalNumber.ToString().Split('.')[1]) != 0)
                    MyRoundedNumber++;

如果你想将负数向下舍入,例如将 -1.1 舍入到 -2 使用这个

  int MyRoundedNumber= (int) MyDecimalNumber;
                    if (Convert.ToInt32(MyDecimalNumber.ToString().Split('.')[1]) != 0)
                        if(MyRoundedNumber>=0)
                           MyRoundedNumber++;
                        else
                           MyRoundedNumber--;

【讨论】:

  • 这是一种可怕的方法。转换成字符串,认真的吗?
【解决方案4】:

在说它不起作用之前,您必须检查操作中的ALL VALUES 是否为double 类型。 这是 C# 中的一个示例:

 int speed= Convert.ToInt32(Math.Ceiling((double)distance/ (double)time));

【讨论】:

    【解决方案5】:
    var d = 1.5m;
    var i = (int)Math.Ceiling(d);
    Console.Write(i);
    

    【讨论】:

    • 这只是对数字进行四舍五入,不一定向上
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    相关资源
    最近更新 更多