简体   繁体   English

在C#中测试值是否为数值的正确方法

[英]Proper way to test if a value is numeric in C#

I just need to know if the value is numeric. 我只需要知道值是否为数字。 I don't need to do anything with the value. 我不需要对价值做任何事情。 Is this the best way? 这是最好的方法吗? Feel dirty creating a variable that I won't ever use beyond this: 感觉很脏,创建一个我将永远不会使用的变量:

int val;
if(int.TryParse(txtFoo.Text, out val))
{
    ....
}

Yes, using the relevant TryParse method and ignoring the out parameter is the best way of doing this. 是的,使用相关的TryParse方法并忽略out参数是执行此操作的最佳方法。

You may want to wrap this up into your own set of helper methods (which could specify the appropriate culture etc, if the default isn't right for you) and just return a bool without the out parameter to make them easier to call. 您可能希望将其包装到您自己的一组辅助方法中(如果默认值不合适,可以指定适当的文化等),只返回没有out参数的bool ,以便更容易调用。

Of course, you need to work out what kind of parsing is most appropriate - even for integers, you need to consider whether the range of Int32 is enough for your use case. 当然,您需要确定哪种解析最合适 - 即使对于整数,您还需要考虑Int32的范围是否足以满足您的使用需求。 In my experience, most numeric input has its own "natural" range of valid values, which is unlikely to be exactly the range of any predefined type. 根据我的经验,大多数数字输入都有自己的“自然”有效值范围,这不太可能完全是任何预定义类型的范围。 You may therefore want to expand your helper methods to include the range of valid values to accept. 因此,您可能希望扩展辅助方法以包括要接受的有效值范围。

It's not as flexible as int.TryParse , but you could check to see if each character is a number: 它不像int.TryParse那样灵活,但您可以检查每个字符是否是数字:

bool isInt = txtFoo.Text.All(c => char.IsNumber(c));

In general, though, I would recommend sticking with int.TryParse . 但总的来说,我建议坚持使用int.TryParse You can even call the unused parameter "ignored" to be explicit about your intent, eg: 您甚至可以调用未使用的参数“忽略”来明确您的意图,例如:

int ignored;
bool isInt = int.TryParse(txtFoo.Text, out ignored);

That's the best way of doing it in my knowledge - that's what our company standards adhere to anyway due to the error handling being done within the parsing. 这是我所知道的最佳方式 - 这就是我们公司标准所遵循的原因,因为在解析过程中完成了错误处理。

This details the advantages: http://www.dotnetperls.com/int-tryparse 这详细介绍了优点: http//www.dotnetperls.com/int-tryparse

That is the recommended way of doing it in C#. 这是在C#中执行此操作的推荐方法。 However, you could also add Microsoft.VisualBasic.dll as a reference to your project and then use Microsoft.VisualBasic.Information.IsNumeric() 但是,您也可以添加Microsoft.VisualBasic.dll作为项目的引用,然后使用Microsoft.VisualBasic.Information.IsNumeric()

You can use Regular expressions 您可以使用正则表达式

Regex _isNumber = new Regex(@"^\d+$");
_isNumber.IsMatch(txtFoo.Text);

This will only match Ints, but you can write one that also matches decimals. 这只会匹配Ints,但您可以编写一个也匹配小数。

"is numeric" is an ambiguous term. “是数字”是一个含糊不清的术语。

  • Culture-aware? 文化意识?
  • Allow thousands and/or decimal separators? 允许数千和/或小数分隔符?
  • Allow scientific notation? 允许科学记数法?
  • Allow a sign (before? after?...) 允许一个标志(之前?之后?......)
  • What range of values do you allow? 您允许哪些值? Signed 32-bit integer (Int32.TryParse), Unsigned 32-bit integer (UInt32.TryParse), decimal, double, ... 有符号32位整数(Int32.TryParse),无符号32位整数(UInt32.TryParse),十进制,双精度,...

Hence there is no "best" way, and the Framework provides a multitude of different ways to parse numbers. 因此,没有“最佳”方式,框架提供了多种不同的方法来解析数字。

bool test (string teststring) 
 { for (i=0;i==teststring.length;i++){
   if instr("0123456789.,-+Ee",teststring.substring(i,1) <0){return false;}
   // some additional tests below here if you like
   return true;
 }

however E1001E12e.12e would be noted as a number a little bit more magic is needed to do a clean check, but then you might be able to determine if its a int or a float too.. 然而,E1001E12e.12e会被注意为一个数字,需要更多的魔法来进行干净的检查,但是你可能能够确定它是一个int还是一个浮点数...

您可以尝试使用正则表达式解析来确定字符串中没有非数字字符,或者您可以根据输入使用Int.TryParse(),Double.TryParse(),Float.TryParse()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM