Przemek Wojtas
Przemek Wojtas

Reputation: 1371

Checking if a number entered has an integer value

First of all I am a beginner in C#, I have just started to play around with it as that's what my University course requires.

My problem is an assignment question which says:

h) To test if a number entered has an integer value. Hint: The number will have to be of type Double. If, for example, the number is 2.5 that doesn’t have an integer value but 2 does. You will need to use Convert.ToInt32(TheNumber) to convert the Double to an Int then compare the two.

double a, b, result;
            Console.WriteLine("Input a number");
            a = Convert.ToDouble(Console.ReadLine());
            b = Convert.ToInt32(a);

This is what I have at the moment and I don't know how to compare these 2 to test which one is an integer. I am pretty sure that you have to use an if statement but how to tell C# to test which of these 2 numbers is an integer and which one isn't!

Any help is highly appreciated :)

Upvotes: 3

Views: 10393

Answers (5)

Tomas Paul
Tomas Paul

Reputation: 540

I would use '%' operator.

double number = 3.1;
bool isInteger = (number % 1) == 0;
string result = isInteger ? "" : "NOT ";
Console.WriteLine($"Number '{number}' is {result}integer.");

Upvotes: 0

DrKoch
DrKoch

Reputation: 9772

Update:
I'd do it like this:

double d;
int i;
Console.WriteLine("Input a number");
d = Convert.ToDouble(Console.ReadLine());
i = Convert.ToInt32(d);
if(i == d) Console.WriteLine("It is an integral value");

This means: if you convert a double to an integer, it will lose all its digits after the decimal point. If this integer has the same value as the double, then the double had no digits after the decimal point, so it has an integer value.

Upvotes: 6

Dalim Mohammad
Dalim Mohammad

Reputation: 43

I think you can use TryParse with do while loop

int  number;
string value;
do
{
  Console.Write("Enter a number : ");
  value =Console.ReadLine();

  if (!Int32.TryParse(value, out number))
       {
         Console.WriteLine("Wrong Input!!!!");
       }

}while (!Int32.TryParse(value, out number));

Upvotes: 0

Hong
Hong

Reputation: 1

Should be like this:

double d;
int i;      
Console.WriteLine("Input a number");
d = Convert.ToDouble(Console.ReadLine());
i = Convert.ToInt32(d);
if(i == d) Console.WriteLine("It is an integral value");

Upvotes: 0

Haseeb Asif
Haseeb Asif

Reputation: 1786

You can use TryParse method which returns boolean

        double mydouble;
        int myInt;
        string value = Console.ReadLine();
        if (double.TryParse(value, out mydouble))
        {
            //This is double value, you can perform your operations here
        }
        if (int.TryParse(value, out myInt))
        {
            //This is Int value, you can perform your operation here
        }

Upvotes: 4

Related Questions