Decimal/double to integer - round up (not just to nearest)

喜夏-厌秋 提交于 2020-01-03 06:48:10

问题


How would you round up a decimal or float to an integer. For instance...

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

Etc.


回答1:


Simple, use Math.Ceiling:

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



回答2:


Something like this?

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



回答3:


Math.Ceiling not working for me, I use this code and this work :)

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

and if you want to round negative number to down for example round -1.1 to -2 use this

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



回答4:


Before saying it does not work, you have to check that ALL VALUES in the operation are double type. Here is an example in 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);


来源:https://stackoverflow.com/questions/8666069/decimal-double-to-integer-round-up-not-just-to-nearest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!