Jacob Filtenborg
Jacob Filtenborg

Reputation: 137

C# Validate input as double

I would like to validate my input as bigger than or equal to 0 and as double. This is what i have so far:

string aBalBeginS;
double abalbeginVal;

Console.Write("Account Balance at the beginning: $");
aBalBeginS = Console.ReadLine();
abalbeginVal = double.Parse(aBalBeginS);
if (aBalBeginS == "" || abalbeginVal <= 0)
{
   Console.WriteLine("Invalid data entered - no value redorded");
   aBalBeginS = null;
}

How do i add to check if input is a number. I tried double.TryParse, but without luck.

Upvotes: 1

Views: 2345

Answers (2)

Eric J.
Eric J.

Reputation: 150108

You are on the right track with double.TryParse()

double abalbeginVal;
bool parsed = double.TryParse(aBalBeginS, out abalbeginVal);
if (parsed && abalbeginVal >=0.0)
{
    // We're good
}
else
{
    // Did not pass check
}

Upvotes: 3

Jacob Filtenborg
Jacob Filtenborg

Reputation: 137

Found the solution:

Console.Write("Account Balance at the beginning: $");
            aBalBeginC = Console.ReadLine();

            //abalbeginVal = double.Parse(aBalBeginC);
            if (double.TryParse(aBalBeginC, out abalbeginVal) == false || aBalBeginC == "" || abalbeginVal <= 0)
            {
                Console.WriteLine("Invalid data entered - no value redorded");
                aBalBeginC = null;
            }

Thx.

Upvotes: 0

Related Questions