Identify if a string is a number

前端 未结 25 3076
無奈伤痛
無奈伤痛 2020-11-22 00:13

If I have these strings:

  1. \"abc\" = false

  2. \"123\" = true

  3. \"ab2\"

25条回答
  •  别那么骄傲
    2020-11-22 00:20

    If you want to check if a string is a number (I'm assuming it's a string since if it's a number, duh, you know it's one).

    • Without regex and
    • using Microsoft's code as much as possible

    you could also do:

    public static bool IsNumber(this string aNumber)
    {
         BigInteger temp_big_int;
         var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
         return is_number;
    }
    

    This will take care of the usual nasties:

    • Minus (-) or Plus (+) in the beginning
    • contains decimal character BigIntegers won't parse numbers with decimal points. (So: BigInteger.Parse("3.3") will throw an exception, and TryParse for the same will return false)
    • no funny non-digits
    • covers cases where the number is bigger than the usual use of Double.TryParse

    You'll have to add a reference to System.Numerics and have using System.Numerics; on top of your class (well, the second is a bonus I guess :)

提交回复
热议问题