數(shù)據(jù)類型轉(zhuǎn)化
精度指小數(shù)點(diǎn)后面的精確度)
條件: 數(shù)據(jù)要兼容,都是值類型
? ? ? ? ? ? 從取值范圍小的往大的轉(zhuǎn) (低精度到高精度)
?一、隱式轉(zhuǎn)化(低精度轉(zhuǎn)化為高精度)
//加f表示單精度
// float a = 1;
// double b = 1.2f;
二、強(qiáng)制轉(zhuǎn)化
從取值范圍大的向小的轉(zhuǎn)化需要進(jìn)行強(qiáng)制轉(zhuǎn)換,其缺點(diǎn)是精確度會(huì)丟失;
1、使用(類型名)變量名進(jìn)行強(qiáng)制轉(zhuǎn)換
float a = 10.4f;
int b = (int )a;//a = 10 ;精度丟失
2、使用Parse方法.一般用于轉(zhuǎn)換string
string? str = "123";
b = int.Parse(str);//括號(hào)里面寫字符串
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)) { ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //如果轉(zhuǎn)換成功 輸出C
Console.WriteLine ("{0}", c);
} else {
Console.WriteLine ("failure");
//失敗輸出 falilure
}
3、使用Convert類方法
(把string類型轉(zhuǎn)化為int //如果有字符的話會(huì)轉(zhuǎn)換失?。?/b>
string? str = "123";
int c = 0;
c =? Convert.ToInt32(str);
Console.WriteLine ("{0}",c);
4、其他類型轉(zhuǎn)為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ù)點(diǎn)后的數(shù)字)
// a = (float)b;//以上a為單精度 b 為雙精度
轉(zhuǎn)化方式寫在轉(zhuǎn)化目標(biāo)前面
單雙精度不是說(shuō)小數(shù)點(diǎn)后的幾位數(shù),而是精確程度的區(qū)別
// string num ="123";
// int d = int.Parse(num);//字符串轉(zhuǎn)化為int類型
注!可能會(huì)強(qiáng)轉(zhuǎn)失敗 例如當(dāng)string里面有字母的情況下