How to Validate Should-Be-Numeric String?

ellpee

Active member
Joined
Apr 16, 2023
Messages
27
Programming Experience
10+
Simple console app, user is supposed to enter a percentage, so 20 or 20% is fine, have code to deal with that as well as no entry at all. But if user enters rubbish -- "twenty percent" or "fifty/fifty" or "xyzpdq" or whatever, how can I test whether his entry can be interpreted as a numeric?
 
int.TryParse() is what professional programmers use, if they don't have to deal with the percent sign. If the percent sign is acceptable, then try will use a regular expression to check for an acceptable matching pattern, as well as to extract that numeric part to later be passed on to int.TryParse(). Most beginners will use int.Parse() or Convert.ToInt32() and catch the exception.
 
If the user may or may not enter a % symbol, I'd be tempted to just Trim that from the end of the string first, then feed the rest into TryParse. If that's all you do, that would actually allow multiple % symbols at the end of the input, but that might be OK anyway.
 
int.TryParse() is what professional programmers use, if they don't have to deal with the percent sign. If the percent sign is acceptable, then try will use a regular expression to check for an acceptable matching pattern, as well as to extract that numeric part to later be passed on to int.TryParse(). Most beginners will use int.Parse() or Convert.ToInt32() and catch the exception.

Well, I'm definitely a beginner! The user is asked for a percentage, so he could enter either 20 or 20%, and I want that to cast to decimal .20. Maybe the easy path is to just change my prompt so he'll only enter 20.
 
Somewhat to my surprise, I found out that Convert.ToDecimal(userinput) / 100; works just fine for both 20 and 20%, no trimming needed. Yay! Still have to deal with the "isn't numeric at all" problem, but this one is well and truly solved. Thanks, all.
 
Still have to deal with the "isn't numeric at all"

C#:
        var input = "123.45%";
        if(decimal.TryParse(input.TrimEnd('%'), out var d))
            Console.WriteLine(input[^1] == '%' ? d / 100 : d); //if the value entered ends in %, actually make it a percentage, otherwise take it as given
        else
            Console.WriteLine("Enter a valid decimal value, optionally followed by a trailing percent symbol");

You can take out the "input[^1] == '%' ? d / 100 : d" bit and just write d if 20 or 20% truly means 20% in all cases


works just fine for both 20 and 20%
Didn't in my tests on various frameworks, but feel free to remove the trim if it works for you
 
Last edited:

Latest posts

Back
Top Bottom