c#中Convert中沒有ToFloat()方法。
將string轉化成float可以採用下面的方法 float.Parse()方法,相應的int.Parse()方法。
float ratio = score / point * 100;
ratio.ToString("f1");
可以使用上面的方法將float轉化成帶一位小數的字符串
以下文章轉自:http://blog.csdn.net/best_02/archive/2007/08/31/1766737.aspx
作者郵箱:[email protected]
對於初學者來說,在編寫c#程序時最頭痛的就是要進行各種數據類型的轉換,
由於對.net開發環境的不熟悉以及系統提供的API的不瞭解,在處理程序時佔用
了很長的時間,筆者雖然做c#的開發時間不長,但對數據之間的轉化也有了一
定的心得,現在共享出來希望對大家能有所幫助。
1.int型轉化爲string
int i;//i可根據自己的需要進行初始化
string a = i.ToString();
2.string轉化爲byte[]
方法1:
string t;//要轉化的字符串
char[] m = t.ToCharArray();
byte[] n = new byte[m.Length];//轉化的結果數組
for ( i = 0; i < m.Length; i++)
{
n[i] = (byte)m[i];
}
方法2:
利用系統提供的函數
string str;
Byte[] bt = System.Text.Encoding.ASCII.GetBytes(str.ToCharArray);
3.int型轉化爲byte[]
方法1:
int i;
byte[] temp = new byte[4];
int pos;
for (pos = 0; pos < 4; pos++)
{
temp[pos] = (byte)(i & 0xff);
i >>= 8;
if (i == 0) break;
}
方法2:
利用系統提供的函數
int i;
byte[] tdata = new byte[4];
data = System.BitConverter.GetBytes(i);
4.byte[]轉化爲string
方法1:
byte[] tmp;
string str =new System.Text.ASCIIEncoding ().GetString (tmp );
方法2:
byte[] tmp;
string str = System.Text.Encoding.ASCII.GetString(tmp);
5.string類型轉化爲int
方法1:
string str;
int i = Convert.ToInt32(str);
方法2:
string str;
int i = Int32.Parse(str);
6.byte[]轉換爲int
方法1:
int res = 0; //結果
int temp = 0;
byte[] result;//可由上文得到,或自己進行初始化
for (int h = 3; h>=0; h--)
{
res<<= 8;
temp = result[h] & 0xff;
res |= temp;
}
方法2:
byte[] result;
int res = System.BitConverter.ToInt32(result,result想轉化的起始位置);
以下文章轉自:http://blog.csdn.net/bEst_02/archive/2007/09/01/1768318.aspx
從小端大端問題剖析數據類型轉化
********** **********
* 1 Byte * <-----------* 1 Byte * 低位
********** ********** |
* 1 Byte * |
********** |
* 1 Byte * |
********** |
* 1 Byte * 高位
**********
* 78 * 低位
********** |
* 56 * |
********** |
* 34 * |
********** |
* 12 * 高位
**********
* 12 * 低位
********** |
* 34 * |
********** |
* 56 * |
********** |
* 78 * 高位
**********