1.判斷是否為數值 TryParse
- 若要檢查輸入的資料是否為數值,可呼叫數值型別的TryParse()方法檢查資料內容是否為數值。符合回傳True,只要出現數字以外的則回傳False
public partial class Training1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string s1 = "三百"; string s2 = "1000"; string s3 = "2,000"; string s4 = "-3000"; string s5 = "4000d"; int currentValue = 0; Response.Write(int.TryParse(s2,out currentValue)+"-"+currentValue+" ; "); Response.Write(int.TryParse(s3,out currentValue)+"-"+currentValue+" ; "); Response.Write(int.TryParse(s4,out currentValue)+"-"+currentValue+" ; "); Response.Write(int.TryParse(s5,out currentValue)+"-"+currentValue+" ; "); } }
結果:
True-1000 ; False-0 ; True--3000 ; False-0 ;
2.數值的格式化 decimal
- 幾乎每個物件都會提供ToString()方法,用來將物件內容轉換成字串表示
- 如果要將數字實數常值當成decimal處理,請使用後至字元m或M,例如
decimal d = 12345.67M;
如果沒有後置字元M,數字會被視為double處理,因而產生錯誤 - 整數常值來初始化字元則不需要M,例如
decimal d = 1234567;
數值格式名稱
|
範例
|
例子
|
G或g
|
123456.789
|
123456.789為例
|
C或c
|
NT$123456.789
|
123456.789為例
|
G或g
|
123456.789
|
123456.789為例
|
F或f
|
123456.79
|
123456.789為例
|
N或n
|
123,456.789
|
123456.789為例
|
P或p
|
24.13%
|
0.24125為例
|
E或e
|
1234568E+005
|
0.24125為例
|
X
|
7B
|
123為例
|
x
|
7b
|
123為例
|
3.資料型別轉換 Convert.
ToBoolean
|
轉換為bool型別
|
ToByte
|
轉換為byte型別
|
ToChar
|
轉換為Char型別
|
ToDateTime
|
轉換為DateTime型別
|
ToDouble
|
轉換為double型別
|
ToDecimal
|
轉換為decimal型別
|
ToInt32
|
轉換為int型別
|
ToInt64
|
轉換為long型別
|
ToInt16
|
轉換為Short型別
|
ToString
|
轉換為String型別
|
- 隱含式資料型別轉換
數值在不同變數之間傳遞時,需要從某種形別轉換成另一種型別來處理,例:
int a = 123;
long b = a; - 明確式資料型別轉換
當資料從較大的資料型別轉換成較小的變數中使用,可能會造成資料損失,會產生錯誤
例:
int a = 12;
byte b = (byte) a;
- 建議使用資料轉換時,盡可能使用明確式資料轉換
沒有留言:
張貼留言