dotnet的旧版框架的四舍五入和通常理解的四舍五入是不同的,以下的代码解决了这个问题
// 四舍五入
public static decimal Round(this decimal num, int decimals)
{
decimal precision = (decimal)Math.Pow(10.0, decimals + 1);
return RoundDown(num + 5 * 1 / precision, decimals);
}
// 向上舍入
public static decimal RoundUp(this decimal num, int decimals)
{
decimal precision = (decimal)Math.Pow(10.0, decimals);
return RoundDown(num, decimals) + 1 / precision;
}
// 向下舍入
public static decimal RoundDown(this decimal num, int decimals)
{
decimal precision = (decimal)Math.Pow(10.0, decimals);
return ((int)(num * precision)) / precision;
}
// 四舍五入
public static double Round(this double num, int decimals)
{
double precision = (double)Math.Pow(10.0, decimals + 1);
return RoundDown(num + 5 * 1 / precision, decimals);
}
// 向上舍入
public static double RoundUp(this double num, int decimals)
{
double precision = Math.Pow(10.0, decimals);
return RoundDown(num, decimals) + 1 / precision;
}
// 向下舍入
public static double RoundDown(this double num, int decimals)
{
double precision = (double)Math.Pow(10.0, decimals);
return ((int)(num * precision)) / precision;
}