Hi everybody,

I'm starting to work with C#, almost every doubt I've had, I've found it in forums or tutorials in Internet, but there is one that I don't. How can I check if a string value is a number?

I have a function that returns a string and I need to know if this value is a number or not. How can I do this? :rolleyes: The number could be from 0 to 100.

Thanks a lot!!!

Dani AI

Generated

asked how to tell whether a string is a number (0–100). Earlier replies pointed at user helpers and mentioned TryParse (thanks and ). The most robust pattern is: (1) do a safe parse that does not throw, (2) check the parsed value is in range, and (3) consider culture/formatting if input may contain decimals, thousands separators, or currency.

A reliable integer example (handles null/whitespace and avoids exceptions):

using System.Globalization;

string s = /* input */;
if (!string.IsNullOrWhiteSpace(s)
    && int.TryParse(s.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)
    && n >= 0 && n <= 100)
{
    // n is an integer between 0 and 100
}
else
{
    // not numeric in the required range
}

If fractional numbers are allowed, use double.TryParse or decimal.TryParse with appropriate NumberStyles and a CultureInfo that matches the user input. A short regex can be used to pre-check simple formats (digits only) but always follow it with a TryParse to get the numeric value and do range checks. Avoid Parse or Convert on untrusted input because they throw exceptions on bad input.

For ASP.NET model validation prefer declarative checks like [Range(0,100)] on properties for server-side validation and combine with client-side validation for better UX.

See the official docs for details: Int32.TryParse, NumberStyles, CultureInfo, Regex.IsMatch, and RangeAttribute.

Recommended Answers

All 4 Replies

Perhaps this will help you:

Let me know :).

commented: Great Post! +7

Right!!
It works perfect (at least for me)... :)

Thanks tayspen!!!

See you ... :lol:

int.TryParse(string s, out bool b) is another great function that returns a boolean value to check if string is numeric or not.

commented: 4 years too late. -1

Please do not resurrect old / solved threads. If you have any questions please ask. .... You are welcome to start your own threads.

Thread Closed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.