四舍五入到小数点后2位,不使用银行家';s取整

本文关键字:银行家 取整 小数点 2位 四舍五入 | 更新日期: 2023-09-27 18:27:32

.NET和Compact Framework默认使用银行四舍五入,这意味着值:1165将四舍五入为:1,16。

相反,sqlserver将其四舍五入为1,17,因为对我来说,这是正确的行为。

有没有人遇到过这个话题,并为Compact Framework找到了解决方法?(在.net中,有一个附加参数对舍入行为有影响)

四舍五入到小数点后2位,不使用银行家';s取整

Math.Floor(double)似乎是受支持的,所以;

private static double RoundToTwo(double value)
{
    return Math.Floor(100*value + .5)/100;
}
Console.WriteLine(RoundToTwo(1.165));
> 1.17
Console.WriteLine(RoundToTwo(1.16499));
> 1.16

这里有一个可以代替decimal.round使用的方法:

public static decimal RoundHalfUp(this decimal d, int decimals)
{
if (decimals < 0)
{
    throw new ArgumentException("The decimals must be non-negative", 
        "decimals");
}
decimal multiplier = (decimal)Math.Pow(10, decimals);
decimal number = d * multiplier;
if (decimal.Truncate(number) < number)
{
    number += 0.5m;
}
return decimal.Round(number) / multiplier;
}

摘自:为什么.NET使用banker';s默认四舍五入?

这个问题还问了.Net为什么使用银行家取整。所以我相信这将是一本很好的读物。

回答原因

这种bankers算法意味着,当小数==.5时,收集的结果将均匀地向上/向下取整,所以实际上只是为了使数据结果均匀。

这是Skeet 先生描述的另一个链接

尝试

    double number = 1.165;
    string RoundedNumber = number.ToString("f3");

其中3是标度