Reputation:
I want to pass a number and have the next whole number returned,
I've tried Math.Ceiling(3)
, but it returns 3.
Desired output :
double val = 9.1 => 10
double val = 3 => 4
Thanks
Upvotes: 2
Views: 139
Reputation: 21
Usually when you refer to whole number it is positive integers only. But if you require negative integers as well then you can try this, the code will return 3.0 => 4, -1.0 => 0, -1.1 => -1
double doubleValue = double.Parse(Console.ReadLine());
int wholeNumber = 0;
if ((doubleValue - Math.Floor(doubleValue) > 0))
{
wholeNumber = int.Parse(Math.Ceiling(doubleValue).ToString());
}
else
{
wholeNumber = int.Parse((doubleValue + 1).ToString());
}
Upvotes: 0
Reputation: 10818
There are two ways I would suggest doing this:
Using Math.Floor()
:
return Math.Floor(input + 1);
Using casting (to lose precision)
return (int)input + 1;
Fiddle here
Upvotes: 5
Reputation: 374
Using just the floor or ceiling wont give you the next whole number in every case. For eg:- If you input negative numbers. Better way is to create a function that does that.
public class Test{
public int NextWholeNumber(double n)
{
if(n < 0)
return 0;
else
return Convert.ToInt32(Math.Floor(n)+1);
}
// Main method
static public void Main()
{
Test o = new Test();
Console.WriteLine(o.NextWholeNumber(1.254));
}
}
Upvotes: 0