24

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
  • 20,858
  • 36
  • 128
  • 169
  • 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

58

Simple, use Math.Ceiling:

var wholeNumber = (int)Math.Ceiling(fractionalNumber);
George Duckett
  • 30,870
  • 7
  • 96
  • 158
  • 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
  • 56,684
  • 27
  • 122
  • 146
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
  • 891
  • 13
  • 14
0

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
  • 469
  • 3
  • 11
-1
var d = 1.5m;
var i = (int)Math.Ceiling(d);
Console.Write(i);
Vadim Martynov
  • 7,049
  • 5
  • 29
  • 39
ali karaca
  • 11
  • 2