C#值数值类型转换

时间:2022-03-31 11:38:47

1.十进制转16进制

 int number=
string result=number.ToString("X2");
>>0A
//X2表示大写2位

2.字符串转数值类型

 int data = int.Parse("");

3.16进制的字符串转数值类型

注:16进制字符串不能直接转换,因为无法识别当中的字符a~f

 int data = int.Parse("a9", System.Globalization.NumberStyles.AllowHexSpecifier);//指示数值字符串标识16进制

int data = Convert.ToInt16("a9", );

3.科学计数转换为数值类型

将 "9.820E+05" 与 "1.009E-05"转换为数值类型,直接 使用 Convert.ToDouble 的方法

  string strNumber1 = "9.820E+05";
string strNumber2 = "1.009E-05"; double data1 = Convert.ToDouble(strNumber1);
double data2 = Convert.ToDouble(strNumber2)

4.16进制字符串转换为数值并按位比较

 temp = strTemp.Substring(, );
int number = int.Parse(strTemp, System.Globalization.NumberStyles.AllowHexSpecifier);
bool status=(number & 0x8000) == ? false : true;

或者

     char temp = Convert.ToChar(Data.Substring(, ));
if ((temp1 & ) != )
result += "第3个字节的高四位为0010";

5.List数组转换

List<decimal> prices = t.Split(',').Select(n => decimal.Parse(n, style)).ToList();

或者

  string[] arr =["",""];
List<int> intList = Array.ConvertAll<string,int>(arr,s=>int.Parse(s)).ToList();

6.保留两位小数

     double a = , b = 123456.1, c = 123456.12, d = 123456.123, e = 123456.126;
Console.WriteLine(a.ToString("N")); //123,456.00
Console.WriteLine(b.ToString("N")); //123,456.10
Console.WriteLine(c.ToString("N")); //123,456.12
Console.WriteLine(d.ToString("N")); //123,456.12
Console.WriteLine(e.ToString("N")); //123,456.13
Console.WriteLine(); Console.WriteLine(a.ToString("N2")); //123,456.00
Console.WriteLine(b.ToString("N2")); //123,456.10
Console.WriteLine(c.ToString("N2")); //123,456.12
Console.WriteLine(d.ToString("N2")); //123,456.12
Console.WriteLine(e.ToString("N2")); //123,456.13
Console.WriteLine(); Console.WriteLine(a.ToString("F2")); //123456.00
Console.WriteLine(b.ToString("F2")); //123456.10
Console.WriteLine(c.ToString("F2")); //123456.12
Console.WriteLine(d.ToString("F2")); //123456.12
Console.WriteLine(e.ToString("F2")); //123456.13
Console.WriteLine(); Console.WriteLine(a.ToString("0.00")); //123456.00
Console.WriteLine(b.ToString("0.00")); //123456.10
Console.WriteLine(c.ToString("0.00")); //123456.12
Console.WriteLine(d.ToString("0.00")); //123456.12
Console.WriteLine(e.ToString("0.00")); //123456.13
Console.WriteLine(); Console.WriteLine(a.ToString("G")); //
Console.WriteLine(b.ToString("G")); //123456.1
Console.WriteLine(c.ToString("G")); //123456.12
Console.WriteLine(d.ToString("G")); //123456.123
Console.WriteLine(e.ToString("G")); //123456.126
Console.WriteLine(); //本地货币
Console.WriteLine(a.ToString("C")); //NT$123,456
Console.WriteLine(b.ToString("C")); //NT$123,456.1
Console.WriteLine(c.ToString("C")); //NT$123,456.12
Console.WriteLine(d.ToString("C")); //NT$123,456.123
Console.WriteLine(e.ToString("C")); //NT$123,456.126
Console.WriteLine();
Console.Read();