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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…