[英]How to find out a String is an non-digit Integer number?
我需要確定給定的String是否是純整數,這意味着它不是double也不是float。
我試過的是一個正則表達式:
@"^\d+$"
if (Regex.IsMatch(oStreamDataValues[i].ToString(), @"^\d+$") == false)
效果很好,但僅在String包含數字(如0.00)或任何其他數字值之前。
您可以使用TryParse
方法:
int value;
if(int.TryParse(myString, out value)) {
// it is an integer
}
為什么不嘗試使用int.TryParse
解析它:
string s = "-12";
int i;
bool isInt = int.TryParse(s, out i);
如果您還想解析0.00
:
bool isInt;
decimal d;
if (decimal.TryParse(s, out d))
{
if (d % 1 == 0)
{
isInt = true;
}
else
{
isInt = false;
}
}
else
{
isInt = false;
}
如我所見,在您的情況下,一些浮點值是積極的例子
4.00 // <- just 4
1e3 // <- is 1000
1e100 // <- 10...0 (100 zeros)
因此,我建議將其解析為Double
,然后測試小數部分是否為0:
String s = "123.0";
Double v;
if (Double.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out v))
if ((v - Math.Truncate(v)) < Math.Abs(v) / 1.0e20) //TODO: Adjast tolerance here
Console.Write("this is an integer value");
我個人會使用Int32靜態方法來解析String。 有TryParse和Parse(取決於您是否要使用try / catch)。
int returnedNumber = 0;
if(!Int32.TryParse(oStreamDataValues[i].ToString(), out returnedNumber)) {
//enter code here
}
要么
bool isInt = true;
int returnedNumber = 0;
try {
returnedNumber = Int32.Parse(oStreamDataValues[i].ToString());
}
catch(FormatException) {
isInt = false;
}
if(!isInt) {
//enter code here
}
s參數包含以下形式的數字:
[ws] [sign]個數字[ws]
方括號([和])中的項目是可選的。 下表描述了每個元素。
ws可選的空格。
sign可選標志。
digits一系列數字,范圍從0到9。
解析: https : //msdn.microsoft.com/zh-cn/library/b3h1hf19%28v=vs.110%29.aspx
TryParse: https ://msdn.microsoft.com/zh-cn/library/f02979c7%28v=vs.110%29.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.