什么是C#相当于NaN或则IsNumeric的? [英] What is the C# equivalent of NaN or IsNumeric?

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

问题描述

这似乎是一个相当简单的问题,我很惊讶,没有以前必需的。什么是测试字符串输入的最有效的方式是数字(或相反非数字)?我想我可以做一个 Double.Parse 或正则表达式(见下文),但我不知道是否有一个实施的办法做到这一点,如JavaScript的 NAN()则IsNumeric()(是VB,我不记得了?)。

 公共静态布尔则IsNumeric(此字符串值)
{
    返回Regex.IsMatch(价值^ \\\\ D + $);
}


解决方案

这不具有正则表达式的开销

 双myNum的= 0;
字符串的testvar =非数字;如果(Double.TryParse(的testvar,出来的myNum)){
  //这是一个数
}其他{
  //它不是一个号码
}

顺便说一下,所有的标准数据类型,用的GUID的明显异常,支持的TryParse。

更新结果
secretwep长大把值2345,将通过上述测试为一个数字。但是,如果您需要确保所有的字符串中的字符是数字,那么另一种方法不宜服用。

例1

 公共布尔ISNUMBER(String s)将{
  布尔值= TRUE;
  的foreach(在s.ToCharArray()字符C){
    值=价值和放大器;&安培; Char.IsDigit(C);
  }  返回值;
}

如果你想多一点花哨

 公共布尔ISNUMBER(字符串值){
  返回value.All(Char.IsDigit);
}

This seems like a fairly simple question, and I'm surprised not to have required it before. What is the most efficient way of testing a string input is a numeric (or conversely Not A Number)? I guess I can do a Double.Parse or a regex (see below) but I was wondering if there was a implemented way to do it, 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+$");
}

解决方案

This doesn't have the regex overhead

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

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

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

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.

example 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);
}

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

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