Identify if a string is a number

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

If I have these strings:

  1. \"abc\" = false

  2. \"123\" = true

  3. \"ab2\"

25条回答
  •  感动是毒
    2020-11-22 00:21

    I've used this function several times:

    public static bool IsNumeric(object Expression)
    {
        double retNum;
    
        bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
        return isNum;
    }
    

    But you can also use;

    bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
    bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false
    

    From Benchmarking IsNumeric Options


    (source: aspalliance.com)


    (source: aspalliance.com)

提交回复
热议问题