0

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");
J_W
  • 51
  • 4
  • 1
    Sorry, but I'm not really clear what you're trying to do here. Are you trying to check that the user enters a valid float number or...? There are too many backslashes in this regex, for starters. – ggorlen Jun 11 '20 at 03:09
  • I used 4 because of this page https://stackoverflow.com/questions/4025482/cant-escape-the-backslash-with-regex Yes a valid float number would work too if decimal is going to be like this. – J_W Jun 11 '20 at 03:11
  • This code makes no sense. The `decimal.TryParse` will do everything in one go, which means that the use of the regex is redundant and useless. Why would you think you need to check twice whether it's a valid number or not? If either fails, it's not, so checking twice is meaningless. It's like saying *Is your name Bob?*, and then asking *Is Bob your name?*. – Ken White Jun 11 '20 at 03:12
  • Yeah but are backslash literals what you want to match? I think not, but that's just a guess--preferably, show what the input is you want to reject and which you want to accept. – ggorlen Jun 11 '20 at 03:14
  • @KenWhite I just posted both to show that I tried them both but neither worked – J_W Jun 11 '20 at 03:16
  • Still makes no sense. You get the user input into a string, and then try to convert it to a decimal using `TryParse`. That's the only way to do it, and jumping through a dozen hoops isn't going to change things. – Ken White Jun 11 '20 at 03:17
  • Ok, I thought that might be the only option at this point but wanted to check if there was another way I was missing before reformatting. – J_W Jun 11 '20 at 03:21

0 Answers0