How to check if a string is numeric in C#

3 Answers

0 votes
using System;
using System.Text.RegularExpressions;
 
public class Example
{
    public static void Main()
    {
        string str = "84710";
 
        if (Regex.IsMatch(str, @"^\d+$")) {
            Console.WriteLine("Numeric");
        }
        else {
            Console.WriteLine("Not Numeric");
        }
    }
}



 
/*
run:

Numeric

*/

 



answered Mar 28, 2023 by avibootz
0 votes
using System;
using System.Linq;
 
public class Example
{
    public static void Main()
    {
        string str = "84710";
 
        if (str.All(char.IsDigit)) {
            Console.WriteLine("Numeric");
        }
        else {
            Console.WriteLine("Not Numeric");
        }
    }
}



 
/*
run:

Numeric

*/

 



answered Mar 28, 2023 by avibootz
0 votes
using System;

public class Example
{
    public static bool isNumeric(string str) {
        return int.TryParse(str, out int n);
    }
    public static void Main()
    {
        string str = "84710";
 
        if (isNumeric(str)) {
            Console.WriteLine("Numeric");
        }
        else {
            Console.WriteLine("Not Numeric");
        }
    }
}



 
/*
run:

Numeric

*/

 



answered Mar 28, 2023 by avibootz

Related questions

2 answers 283 views
2 answers 273 views
2 answers 287 views
3 answers 371 views
3 answers 375 views
3 answers 473 views
4 answers 467 views
...