tags:

views:

522

answers:

4

Data :

Empcode    Amount
30034      27.25
30034      124

linq code

    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"))

Output

Empcode    Amount
30034       151

The issue is that I must receive 151**.25** but the output is just 151.

How to avoid this rounding of?

A: 

It seems Sum treats the values as integers which causes the rounding. You could either try and typecast the values to floats or provide a type argument to the sum function to use floats. Note - I'm not a VB developer so things might be a bit different than I expect.

Morten Christiansen
A: 

I am not sure(I do not know language of your snippet), but try something like

Group.Sum(Function(p) p.Field(Of Decimal)("Amount"))

Or

Group.Sum(Function(p) p.Field(Of Double)("Amount"))

Form your results seems that Sum is invoked with Integer

Mike Chaliy
A: 

Used Cdbl and the issues is solved

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")))

EDIT: Cdbl was giving output for some 1.05 as 1.1 as 1.150000000006 so used CDec instead

Sachin
+1  A: 

Hard to tell from your snippet, the problem could be the type of the Amount column or the way you display the result. Consider this equivalent code that doesn't have the problem:

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
Hans Passant