Daryl Gill
Daryl Gill

Reputation: 5524

C# Float does not insert as exact value

When inserting a float into a SQL Server database, I'm getting:

5.03000020980835

Which is not the exact value which is being gathered.

How I'm gathering this float? Through a text box control to be converted to float

How I'm working with the data currently:

   private void PayRateTextBox_TextChanged(object sender, EventArgs e)
   {
       PayRateBox = float.Parse(PayRateTextBox.Text);
   }

The above is setting an internal float to the current updated textbox which is set:

 private float PayRateBox = 0;

Then inserted as:

string Query = "INSERT INTO shifts (ShiftDate,WeekNumber,Hours,PayType,Rate) " + 
               "VALUES(@Date, @WeekNo, @Hours, @PayType, @Rate)";

and bound to the query via bound parameters:

CMD.Parameters.Add("@Rate", SqlDbType.Float);
CMD.Parameters["@Rate"].Value = PayRate;

The default text in the TextBox is set to 5.03, so somewhere along the lines other data is being appended to make the overall value increment. I have tried to trace where this is happening, but cannot find out how and why this is happening. Perhaps I'm overlooking something?

Upvotes: 1

Views: 2116

Answers (1)

Michal Hosala
Michal Hosala

Reputation: 5697

Precision of float is limited to 7 significant digits. In your case it means 5.030000. Values at the rest of decimal places are undefined.

To improve precision use either double with precision of 15-16 significant digits or decimal with 28-29 significant digits.

Upvotes: 4

Related Questions