How can I check if a string is a number?

Look up double.TryParse() if you’re talking about numbers like 1, -2 and 3.14159. Some others are suggesting int.TryParse(), but that will fail on decimals.

string candidate = "3.14159";
if (double.TryParse(candidate, out var parsedNumber))
{
    // parsedNumber is a valid number!
}

EDIT: As Lukasz points out below, we should be mindful of the thread culture when parsing numbers with a decimal separator, i.e. do this to be safe:

double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var parsedNumber)

Leave a Comment