verify user input is a double in csharp

To verify if user input is a double in C#, you can use the double.TryParse or double.Parse method.

double.TryParse returns a boolean value indicating whether the conversion was successful, and the parsed value is returned as an out parameter.

Here is an example:

main.cs
string userInput = "3.14";
double parsedValue;
bool isDouble = double.TryParse(userInput, out parsedValue);

if(isDouble)
{
    Console.WriteLine($"Parsed value is: {parsedValue}");
}
else
{
    Console.WriteLine("User input is not a valid double.");
}
253 chars
13 lines

Alternatively, you can use double.Parse, which throws an exception if the input is not a valid double.

main.cs
string userInput = "3.14";
try
{
    double parsedValue = double.Parse(userInput);
    Console.WriteLine($"Parsed value is: {parsedValue}");
}
catch (FormatException)
{
    Console.WriteLine("User input is not a valid double.");
}
231 chars
11 lines

Note that double.Parse can also throw other exceptions, like ArgumentNullException or OverflowException.

gistlibby LogSnag