问题
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