How can I check if a string is a number?

后端 未结 25 1861
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 21:04

I\'d like to know on C# how to check if a string is a number (and just a number).

Example :

141241   Yes
232a23   No
12412a   No

an

25条回答
  •  盖世英雄少女心
    2020-11-27 21:34

    The problem with some of the suggested solutions is that they don't take into account various float number formats. The following function does it:

    public bool IsNumber(String value)
    {
        double d;
        if (string.IsNullOrWhiteSpace(value)) 
            return false; 
        else        
            return double.TryParse(value.Trim(), System.Globalization.NumberStyles.Any,
                                System.Globalization.CultureInfo.InvariantCulture, out d);
    }
    

    It assumes that the various float number styles such es decimal point (English) and decima comma (German) are all allowed. If that is not the case, change the number styles paramater. Note that Any does not include hex mumbers, because the type double does not support it.

提交回复
热议问题