數(shù)據(jù)類型轉化
精度指小數(shù)點后面的精確度)
條件: 數(shù)據(jù)要兼容,都是值類型
? ? ? ? ? ? 從取值范圍小的往大的轉 (低精度到高精度)
?一、隱式轉化(低精度轉化為高精度)
//加f表示單精度
// float a = 1;
// double b = 1.2f;
二、強制轉化
從取值范圍大的向小的轉化需要進行強制轉換冷溶,其缺點是精確度會丟失管削;
1蒜哀、使用(類型名)變量名進行強制轉換
float a = 10.4f;
int b = (int )a;//a = 10 ;精度丟失
2彪置、使用Parse方法.一般用于轉換string
string? str = "123";
b = int.Parse(str);//括號里面寫字符串
Console.WriteLine("{0}",b);
string? str = "123.2";
float b = float.Parse(str);
Console.WriteLine("{0}",b);
避免崩潰 int.Try.Parse (str拄踪,out )
string? str = "123a";
int c = 0;
bool b;
if (b = int.TryParse (str, out c)) { ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //如果轉換成功 輸出C
Console.WriteLine ("{0}", c);
} else {
Console.WriteLine ("failure");
//失敗輸出 falilure
}
3、使用Convert類方法
(把string類型轉化為int //如果有字符的話會轉換失斎)
string? str = "123";
int c = 0;
c =? Convert.ToInt32(str);
Console.WriteLine ("{0}",c);
4宫蛆、其他類型轉為string類型 ?.Tostring()
int d = 45;float m = 53.2131f;
string str1 = 1234.ToString ();
string str2 = d.ToString ();
string str3 = m.ToString ();
Console.WriteLine (str);
// int c = (int)1.4f;//(不是四舍五入,直接抹掉后面小數(shù)點后的數(shù)字)
// a = (float)b;//以上a為單精度 b 為雙精度
轉化方式寫在轉化目標前面
單雙精度不是說小數(shù)點后的幾位數(shù)的猛,而是精確程度的區(qū)別
// string num ="123";
// int d = int.Parse(num);//字符串轉化為int類型
注耀盗!可能會強轉失敗 例如當string里面有字母的情況下