1

What I would like is to basically have the user enter in a float, and then the system check that the input is indeed a float, and if it is then it will proceed with the code, and if it is not then the user will have to re-input the with the correct data type. Sorry for the beginners question, an example of the code is:

            Console.Write("Response Value > ");
            Response = float.Parse(Console.ReadLine())

            Ask_Count = Ask_Count + 1;
            if (Response > 0 && Response < 6)
            {
                Valid_Count = Valid_Count + 1;
            }

How would I go about the program checking to see if Response is a float?

Thank you.

2 Answers 2

8

Use float.TryParse for it.

Console.Write("Response Value > ");
if(float.TryParse(Console.ReadLine(), out Response)
{
    Ask_Count = Ask_Count + 1;
    if (Response > 0 && Response < 6)
        Valid_Count = Valid_Count + 1;
}
else
    Console.WriteLine("Number entered is not a float");
Sign up to request clarification or add additional context in comments.

2 Comments

While correct, perhaps it would be more useful if you included a link to MSDN and/or showed how this would integrate with the current code? Just giving a method name isn't really an answer.
@AlexanderR: I was writing it. check out.
2

another is by using is float.

bool result = varName is float;

or

float x = 0;
bool result = float.tryParse(varname, out x);

1 Comment

Not for this particular scenario. Console.ReadLine() will always return a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.