Checking if an object is a number in C#

前端 未结 11 1589
粉色の甜心
粉色の甜心 2020-11-29 19:35

I\'d like to check if an object is a number so that .ToString() would result in a string containing digits and +,-,.

11条回答
  •  感情败类
    2020-11-29 20:22

    If your requirement is really

    .ToString() would result in a string containing digits and +,-,.

    and you want to use double.TryParse then you need to use the overload that takes a NumberStyles parameter, and make sure you are using the invariant culture.

    For example for a number which may have a leading sign, no leading or trailing whitespace, no thousands separator and a period decimal separator, use:

    NumberStyles style = 
       NumberStyles.AllowLeadingSign | 
       NumberStyles.AllowDecimalPoint | 
    double.TryParse(input, style, CultureInfo.InvariantCulture, out result);
    

提交回复
热议问题