使用 math.truncate() 方法将小数截断为整数,再调用 convert.toint32() 或 (int) 强转即可。该方法直接丢弃小数部分,不进行四舍五入,适用于需要快速取整且忽略精度的场景。

Math.Truncate() 与 (int) 强制转换在处理负数时有何区别
Math.Truncate() 向零方向截断,而 (int) 强制转换在浮点数转整数时也是向零截断,两者行为一致。但需注意 decimal 类型不能直接强转为 int,必须通过 Convert.ToInt32() 或 Math.Truncate() 中转。

using System;
class Program
{
static void Main()
{
decimal pos = 3.7m;
decimal neg = -3.7m;
// 正数处理
int posInt = Convert.ToInt32(Math.Truncate(pos));
Console.WriteLine(posInt); // 输出 3
// 负数处理
int negInt = Convert.ToInt32(Math.Truncate(neg));
Console.WriteLine(negInt); // 输出 -3
}
}
Math.Truncate() 返回值的类型是什么
Math.Truncate() 返回的是 decimal 类型(输入为 decimal 时),即使结果没有小数部分,它仍然是 decimal。因此必须显式转换为 int 或其他整数类型才能用于整数运算或存储。

using System;
class Program
{
static void Main()
{
decimal val = 5.9m;
decimal truncated = Math.Truncate(val);
// 验证类型
Console.WriteLine(truncated.GetType().Name); // 输出 Decimal
// 验证值
Console.WriteLine(truncated); // 输出 5
}
}


















