mercredi 10 juin 2020

Regex and decimal.TryParse are not working to test for decimals

It is late. I am a beginner with C# and have been to six different websites and cannot find the answer to this question. I am trying to test for decimals to make sure the user enters one and not some other character. All of the solutions out there involve string and decimal. How do I just test for decimal. I am not converting a string to a decimal. The below methods worked for testing for strings. Using 4 backslashes did not work either. decimal.TryParse is not working as well. Can someone please offer insight. Thanks.

error 1 Regex: Cannot convert from decimal to string error 2 TryParse: Cannot convert from decimal to System.ReadOnlySpan

Console.WriteLine("Please enter a number");
decimal enteredNumber1 = decimal.Parse(Console.ReadLine());


if (!Regex.IsMatch(enteredNumber1,"^[0-9]\\\\d{0,9}(\\\\.\\\\d{1,3})?%?$"))
{
    Console.WriteLine("Numbers only");
}

if (!decimal.TryParse(enteredNumber1, out enteredNumber1))
    Console.WriteLine("Numbers only");

Aucun commentaire:

Enregistrer un commentaire