25

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.

cllpse
  • 21,396
  • 37
  • 131
  • 170
  • 3
    What behaviour do you want for negative numbers? does -1.1 go to -1 (go to larger) or -2 (go to farther from zero)? – Eric Lippert Dec 29 '11 at 16:25

5 Answers5

59

Simple, use Math.Ceiling:

var wholeNumber = (int)Math.Ceiling(fractionalNumber);
George Duckett
  • 31,770
  • 9
  • 95
  • 162
  • I know it's off-topic, but may I ask you why you used `var` and not `int`? – ken2k Dec 29 '11 at 09:56
  • 3
    Purely out of habit. `var` can be useful when declaring objects of a longer type like `var myDictionary = new Dictionary>()` for example. – George Duckett Dec 29 '11 at 09:57
5

Something like this?

int myInt = (int)Math.Ceiling(myDecimal);
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
1

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));
Manuel Roldan
  • 487
  • 3
  • 12
0

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--;
Mohsen Abdollahi
  • 901
  • 13
  • 14
-1
var d = 1.5m;
var i = (int)Math.Ceiling(d);
Console.Write(i);
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
ali karaca
  • 11
  • 2