1

I am using vb.net to summarize some information in a datatable using the following code.

For some reason the rounding works on all value apart from 1.

Code:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    If TextBox1.Text = "" Then
        'Do Nothing
    Else

        Dim conn As New SqlClient.SqlConnection
        With conn
            .ConnectionString = "server=inlt01\SQLEXPRESS; database=OrbisBilling; integrated security=yes"
            .Open()
        End With

        Dim cmd As New SqlClient.SqlCommand
        With cmd
            .CommandText = "SELECT [Account], [Customer Lookup],ROUND (SUM ([ChargedAmount]),2) as [Sum of Buy Price],ROUND (SUM ([Sell Price]),2) as [Sum of Sell Price],[Tariff Lookup] FROM [OrbisBilling].[dbo].[" + TextBox1.Text + "] GROUP BY [Account], [Customer Lookup],[Tariff Lookup] Order by [Customer Lookup]"
            .CommandType = CommandType.Text
            .CommandTimeout = 30
            .Connection = conn
        End With
        Dim dt As New DataTable
        dt.Load(cmd.ExecuteReader)

        With OrbisViewBillForm.DataGridView1
            .AutoGenerateColumns = True
            .DataSource = dt
        End With

        cmd.Dispose()
        cmd = Nothing
        conn.Dispose()
        conn = Nothing


        OrbisViewBillForm.Show()

    End If
End Sub

As you can see I ROUND the sum for 'Sell Price' by 2 decimal places.

Here is the result.

56.1
1.5899999999999999
133.64
12.67
14.93
0.76
0.57
4.25
2.24
0.06
7.75
4.31
7.96
0.78
0.01
33.55

If rounding to 2, why do I get 1.5899999999999999?

To help troubleshoot I changed the rounding to 3 and get the following inconstancies.

56.1
1.5899999999999999
133.643
12.671
14.928
0.764
0.568
4.253
2.2439999999999998
0.058
7.745
4.306
7.9559999999999995
0.779
0.005
33.554

Any help greatly appreciated.

Thanks,

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
user3580480
  • 442
  • 7
  • 14
  • 45

1 Answers1

3

The SQL Server FLOAT and REAL data types don't store decimal values exactly.

You should consider changing the database columns to DECIMAL or NUMERIC.

Joe
  • 122,218
  • 32
  • 205
  • 338