下面是代码,Model中数值是double类型 但是sum的结果出现是item.Sum = 27.279999999999998
正确结果应该是27.27 后面那些数字为什么多出来了
List<ProductModel> product = new List<ProductModel>();
product.Add(new ProductModel
{
Id = 1,
EnergyId = 2,
Total = 5.34
});
product.Add(new ProductModel
{
Id = 1,
EnergyId = 2,
Total = 5.63
});
product.Add(new ProductModel
{
Id = 1,
EnergyId = 2,
Total = 5.65
});
product.Add(new ProductModel
{
Id = 1,
EnergyId = 2,
Total = 5.72
});
product.Add(new ProductModel
{
Id = 1,
EnergyId = 2,
Total = 4.94
});
var query = from p in product
group p by new
{
p.Id,
p.EnergyId
} into g
select new
{
g.Key,
Sum = g.Sum(p => p.Total)
};
foreach (var item in query)
{
var sum = item.Sum;
}
------解决思路----------------------
https://msdn.microsoft.com/zh-cn/library/system.double.aspx
精度问题,你应该用Math.Round指定精度,而且你的sum应该是27.28
------解决思路----------------------
5.34 + 5.63 + 5.65 + 5.72 + 4.94 = 27.28
Math.Round(27.279999999999998, 2) = 27.28
没有什么很正常
那个 5.63 被 2 除就是无限循环小数,放在计算机里,截尾了 自然是要小一点的