cllpse
cllpse

Reputation: 21727

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

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.

Upvotes: 26

Views: 34119

Answers (5)

Manuel Roldan
Manuel Roldan

Reputation: 525

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));

Upvotes: 1

ali karaca
ali karaca

Reputation: 11

var d = 1.5m;
var i = (int)Math.Ceiling(d);
Console.Write(i);

Upvotes: -1

Mohsen Abdollahi
Mohsen Abdollahi

Reputation: 901

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--;

Upvotes: 0

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

Something like this?

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

Upvotes: 5

George Duckett
George Duckett

Reputation: 32428

Simple, use Math.Ceiling:

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

Upvotes: 60

Related Questions