简体   繁体   中英

TryParse for numbers in C#?

So I want to use a TryParse method, but so far I can do it only with integer or double value. However, I want to check if the value is a number, and if it's not (if it is a string for instance) to get a false value. Something like IsDigit() is Java.

static void Main()
    {
        int number;
        Console.Write("Enter a number: ");
        bool result = Int32.TryParse(Console.ReadLine(), out number); 
        if (result)
        {
            Console.WriteLine("The input number is an integer.");
        }

        else
        {
            Console.WriteLine("The input number is not an integer.");
        }
    }

So I want to do that, but instead of checking for an integer value, I'd like to check for a numerical value. So if anybody can tell me what method I can use I'd be very happy. Thanks in advance!

use double :

double number;
bool result = double.TryParse(Console.ReadLine(), out number); 

This will parse any real number.

TryParse for decimal or double types is your limit for built in methods. If you want more than that, you'd have to parse the string yourself. The can be quite easily done using a regex, such as

^-?[0-9]+\.?[0-9]*([Ee][+-]?[0-9]+)?$

For a single character, there's Char.IsDigit() . In that case you may want to look at Console.ReadKey() instead of reading a whole line. By the way, Char.IsDigit() also matches digits from other cultures .

For multiple characters you'll need to think about what you want to accept. decimals, exponents, negative numbers, or just multiple digit characters?

bool result = double.TryParse(mystring, out num);

double.TryParse也适用于整数。

You could try a regular expression

var regex = new Regex(@"^-*[0-9\.]+$");
var m = regex.Match(text);
if (m.Sucess)
    {
        Console.WriteLine("The input number is an integer.");
    }

    else
    {
        Console.WriteLine("The input number is not an integer.");
    }

You can also allow separators by including them in the regex.

static bool enteredNumber()
{
    int intValue;
    double doubleValue;
    Console.Write("Enter a number: ");
    string input = Console.ReadLine();
    return Int32.TryParse(input, out intValue) ? true : double.TryParse(input, out doubleValue);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM