0

In my SQL Server i have a table with a column called FloatValue With a Float data type.
I update this value from a WCF service with this method:

public int UpdateConfig(float value)
    {
        try
        {
            using (SqlConnection conn = GetConnection(DbName.Temp))
            {
                conn.Open();
                string command = @"UPDATE ConfigTable SET FloatValue = @value";
                using (SqlCommand cmd = new SqlCommand(command, conn))
                {
                    cmd.Parameters.AddWithValue("@value", value);
                    int res = cmd.ExecuteNonQuery();
                    return res;
                }
            }
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

My problem is that when invoking this method like so:

UpdateConfig(1.1);

a select statement like this:

SELECT ConfigTable.FloatValue From ConfigTable

returns this value: 1.10000002384186

When updating this value directly from SSMS the correct data is being updated.
How can i solve this?

Yoav
  • 3,326
  • 3
  • 32
  • 73
  • Perhaps you should use a `double` in code. See http://stackoverflow.com/a/1209190/858757 for more info. – Silvermind Jul 02 '13 at 11:27
  • possible duplicate of [Difference between numeric,float and decimal in sql server](http://stackoverflow.com/questions/1056323/difference-between-numeric-float-and-decimal-in-sql-server) – CodeCaster Jul 02 '13 at 11:28

2 Answers2

1

The reason for this discrepancy is that FLOAT (without specifying N) in SQL Server actually has a precision closer to the double type than to the float type in C#. Using double in your C# code should remove the discrepancy you are seeing.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

This is as expected for a float value. Floats are not exact values so the value 1.1 may indeed be represented by the value 1.10000002384.

One solution would be to round the value to 1 or 2 digits if that is ok. Another solution would be to use a fixed precision number format like Decimal instead.

EDIT:
Actually, the Decimal is not fixed precision, but it is close enough for most use cases.

Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76