数据:
Empcode Amount
30034 27.25
30034 124
linq代码
Dim ComputedData = From p In AllOrders _
Order By p.Field(Of String)("EmpCode") _
Group By Key = p.Field(Of String)("EmpCode") Into Group _
Select EmpCode = Key, _
Consumption = Group.Sum(Function(p) p("Amount"))
输出
Empcode Amount
30034 151
问题是我必须收到151 **。25 **但输出只有151。
如何避免这种四舍五入?
答案 0 :(得分:1)
很难从您的代码段中看出,问题可能是Amount列的类型或显示结果的方式。考虑这个没有问题的等效代码:
Module Module1
Sub Main()
Dim allOrders As New List(Of Order)
allOrders.Add(New Order("30034", 27.25D))
allOrders.Add(New Order("30034", 124))
Dim ComputedData = From p In allOrders _
Order By p.EmpCode _
Group By Key = p.EmpCode Into Group _
Select EmpCode = Key, _
Consumption = Group.Sum(Function(p) p.Amount)
Console.WriteLine("{0:N2}", ComputedData(0).Consumption)
Console.ReadLine()
End Sub
Public Class Order
Public EmpCode As String
Public Amount As Decimal
Public Sub New(ByVal emp As String, ByVal amt As Decimal)
EmpCode = emp
Amount = amt
End Sub
End Class
End Module
答案 1 :(得分:0)
似乎Sum
将值视为导致舍入的整数。您可以尝试将值类型转换为浮点数,或者为sum函数提供类型参数以使用浮点数。注意 - 我不是VB开发人员,所以事情可能与我预期的有点不同。
答案 2 :(得分:0)
我不确定(我不知道你的代码片段的语言),但尝试类似
的内容Group.Sum(Function(p) p.Field(Of Decimal)("Amount"))
或者
Group.Sum(Function(p) p.Field(Of Double)("Amount"))
表单结果似乎是用Integer调用Sum
答案 3 :(得分:0)
使用过Cdbl,问题解决了
Dim ComputedData = From p In AllOrders _
Order By p.Field(Of String)("EmpCode") _
Group By Key = p.Field(Of String)("EmpCode") Into Group _
Select EmpCode = Key, _
Consumption = Group.Sum(Function(p) CDec(p("Amount")))
编辑: Cdbl提供的输出为1.05,1.1为1.150000000006,因此使用CDec代替