NaN 或 IsNumeric 的 C# 等价物是什么? [英] What is the C# equivalent of NaN or IsNumeric?

查看:32
本文介绍了NaN 或 IsNumeric 的 C# 等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试输入字符串是否包含数值(或相反不是数字)的最有效方法是什么?我想我可以使用 Double.Parse 或正则表达式(见下文),但我想知道是否有一些内置的方法可以做到这一点,例如 javascript 的 NaN()IsNumeric()(是那个 VB,我不记得了?).

What is the most efficient way of testing an input string whether it contains a numeric value (or conversely Not A Number)? I guess I can use Double.Parse or a regex (see below) but I was wondering if there is some built in way to do this, such as javascript's NaN() or IsNumeric() (was that VB, I can't remember?).

public static bool IsNumeric(this string value)
{
    return Regex.IsMatch(value, "^\d+$");
}

推荐答案

这没有正则表达式开销

double myNum = 0;
String testVar = "Not A Number";

if (Double.TryParse(testVar, out myNum)) {
  // it is a number
} else {
  // it is not a number
}

顺便说一句,所有标准数据类型(GUID 除外)都支持 TryParse.

Incidentally, all of the standard data types, with the glaring exception of GUIDs, support TryParse.

更新
secretwep 提出值2345"将作为数字通过上述测试.但是,如果您需要确保字符串中的所有字符都是数字,则应采用另一种方法.

update
secretwep brought up that the value "2345," will pass the above test as a number. However, if you need to ensure that all of the characters within the string are digits, then another approach should be taken.

示例 1:

public Boolean IsNumber(String s) {
  Boolean value = true;
  foreach(Char c in s.ToCharArray()) {
    value = value && Char.IsDigit(c);
  }

  return value;
}

或者如果你想变得更花哨

or if you want to be a little more fancy

public Boolean IsNumber(String value) {
  return value.All(Char.IsDigit);
}

update 2(来自@stackonfire 处理空字符串)

update 2 ( from @stackonfire to deal with null or empty strings)

public Boolean IsNumber(String s) { 
    Boolean value = true; 
    if (s == String.Empty || s == null) { 
        value=false; 
    } else { 
        foreach(Char c in s.ToCharArray()) { 
            value = value && Char.IsDigit(c); 
        } 
    } return value; 
}

这篇关于NaN 或 IsNumeric 的 C# 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆