2011-03-29 43 views

回答

1

爲了測試它是否可以被解析爲整數:

int xInt; 


CultureInfo culture = new CultureInfo("en-US");  
bool isInteger = int.TryParse(x, NumberStyles.AllowThousands, culture, out xInt); 

if (isInteger) 
{ 

} 
else 
{ 
string xString = x.ToString(); 
} 
+0

哈哈哈!即使是微不足道的情況,這也會很明顯地失敗。 x =「123.456」也是一個數字! – 2011-04-21 15:30:16

+0

不,不是。但是,「123,456」是。 – AgentFire 2012-02-07 10:08:11

+0

已更新爲包含NumberStyles以解析千位運算符。如果需要,也可以包含小數。 – Russell 2012-02-07 20:27:09

1
int numeric; 
if (int32.TryParse(value, out numeric)) 
{ 
    ... numeric processing 
} 
else 
{ 
    ... alpha numeric processing 
} 
+0

.hehe snap;).. – Russell 2011-03-29 03:23:10

+0

@Russell笑了起來? – 2011-03-29 03:26:20

+1

你可以關閉括號嗎? :) – TheEvilPenguin 2011-03-29 04:30:28

1

有幾個方法可以做到這一點。如果你從數據庫中獲得不同的數據類型,那麼你可以像這樣做一個類型比較;


    Type t = x.GetType(); 
    bool isNumeric t == typeof(sbyte) || 
    t == typeof(byte) || 
    t == typeof(short) || 
    t == typeof(ushort) || 
    t == typeof(int) || 
    t == typeof(uint) || 
    t == typeof(long) || 
    t == typeof(ulong) || 
    t == typeof(float) || 
    t == typeof(double) || 
    t == typeof(decimal); 

這是詳盡的,但它會給你正確的答案。

如果您總是從數據庫中獲取一個字符串,那麼您可以使用一些內置的解析函數,這些解析函數將在大部分時間內運行。

// DO NOT USE 'int.TryParse()' as it will FAIL for any non-integer number, i.e. "123.456" 

decimal d; 
bool isNumeric = decimal.TryParse(x, out d); 

十進制在.NET(內置類型)中具有最廣泛的數字範圍,所以這將涵蓋很多情況。但是,如果您的「號碼」超出了範圍,它仍然可能失敗。例如,假設你有

string n = "5123123189461894481984885646158419999"; 
decimal d; 
bool isNumeric = decimal.TryParse(n, out d); 

即使x表示數字,「ISNUMERIC」會回來爲假,因爲數字是十進制類型的範圍之外。幸運的是,這些情況非常罕見,因此您不必訴諸其他更強烈的字符串解析方法來判斷它是否是數字。 (我現在不打算討論這個問題。)

相關問題