c#各数据类型间的转换
ushort < int < float < double
-
ushort:占用 2 个字节,取值范围为 0 到 65,535。
-
int:占用 4 个字节,取值范围为 -2,147,483,648 到 2,147,483,647。
-
float:占用 4 个字节,取值范围为大约 -3.4 × 10^38 到 +3.4 × 10^38,精度为 7 位有效数字。
-
double:占用 8 个字节,取值范围为大约 -1.7 × 10^308 到 +1.7 × 10^308,精度为 15-16 位有效数字。
-
隐式转换(Implicit Conversion):如果目标数据类型能够容纳源数据类型的所有可能值,并且不会导致数据丢失或精度损失,则可以进行隐式转换,不需要强制转换。例如,将 int类型的值赋给 long 类型的变量时,不需要显式强制转换。
csharpCopy codeint intValue = 100; long longValue = intValue; // 隐式转换,不需要强制转换
-
显式转换(Explicit Conversion):如果目标数据类型的范围比源数据类型小,或者可能导致精度损失,则需要进行显式转换,需要使用强制转换符 (类型)。例如,将 double 类型的值转换为 float`类型时,需要显式强制转换。
csharpCopy codedouble doubleValue = 3.14; float floatValue = (float)doubleValue; // 显式转换,需要强制转换
综上所述,如果目标数据类型的范围更大、精度更高,或者能够容纳源数据类型的所有可能值,通常情况下可以进行隐式转换,不需要强制转换。
ushort类型转换为 double、float 和 int类型
// 定义一个 ushort 变量
ushort ushortValue = 1000;
// 将 ushort 转换为 double 类型
double doubleValue = (double)ushortValue;
// 将 ushort 转换为 float 类型
float floatValue = (float)ushortValue;
// 将 ushort 转换为 int 类型
int intValue = (int)ushortValue;
double、float 和 int类型转换为ushort类型
// 定义一个 int 变量
int intValue = 1000;
// 将 int 转换为 ushort 类型
ushort ushortValueFromInt = (ushort)Math.Max(ushort.MinValue, Math.Min(ushort.MaxValue, intValue));
// 定义一个 double 变量
double doubleValue = 2000.5;
// 将 double 转换为 ushort 类型
ushort ushortValueFromDouble = (ushort)Math.Max(ushort.MinValue, Math.Min(ushort.MaxValue, doubleValue));
// 定义一个 float 变量
float floatValue = 1500.75f;
// 将 float 转换为 ushort 类型
ushort ushortValueFromFloat = (ushort)Math.Max(ushort.MinValue, Math.Min(ushort.MaxValue, floatValue));
//加入double和float类型都是整数
// 定义一个 double 变量表示整数值
double doubleValue = 2000;
// 将 double 转换为 ushort 类型
ushort ushortValueFromDouble = (ushort)doubleValue;
// 定义一个 float 变量表示整数值
float floatValue = 1500;
// 将 float 转换为 ushort 类型
ushort ushortValueFromFloat = (ushort)floatValue;
int转float、int转double
// 定义一个 int 变量
int intValue = 1000;
// 将 int 转换为 float 类型
float floatValue = (float)intValue;
// 将 int 转换为 double 类型
double doubleValue = (double)intValue;
double转int,double转float
// 定义一个 double 变量
double doubleValue = 1000.75;
// 将 double 转换为 int 类型
int intValue = (int)doubleValue;
// 将 double 转换为 float 类型
float floatValue = (float)doubleValue;
float转int,float转double
// 定义一个 float 变量
float floatValue = 1000.75f;
// 将 float 转换为 int 类型
int intValue = (int)floatValue;
// 将 float 转换为 double 类型
double doubleValue = floatValue;
- string 转 double:
csharpCopy codestring stringValue = "3.14";
double doubleValue = double.Parse(stringValue);
2.string 转 float:
csharpCopy codestring stringValue = "3.14";
float floatValue = float.Parse(stringValue);
3.string 转 int:
csharpCopy codestring stringValue = "123";
int intValue = int.Parse(stringValue);
4.string 转 ushort:
csharpCopy codestring stringValue = "123";
ushort ushortValue = ushort.Parse(stringValue);