简体   繁体   English

C#浮点型不作为精确值插入

[英]C# Float does not insert as exact value

When inserting a float into a SQL Server database, I'm getting: 将浮点数插入SQL Server数据库时,我得到:

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 通过一个文本框控件将其转换为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. TextBox中的默认文本设置为5.03,因此沿行添加了其他数据以使总值增加。 I have tried to trace where this is happening, but cannot find out how and why this is happening. 我试图跟踪这种情况的发生,但是无法找到这种情况的发生原因和原因。 Perhaps I'm overlooking something? 也许我忽略了什么?

Precision of float is limited to 7 significant digits. 浮点精度限制为7个有效数字。 In your case it means 5.030000 . 在您的情况下,意味着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. 要提高精度,请使用精度为15-16位有效数字的double或精度为28-29位有效数字的十进制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM