c# - SQL INSERT with ExecuteNonQuery() 插入额外的小数位

标签 c# sql-server

我有一个用 C# 编写的 asp.net 应用程序。我有一个插入按钮,它接受用户在页面上输入的信息,将值添加到列表中,然后将列表发送到将数据插入到 MSSQL 数据库表中的方法。 除了在后端将数据类型设置为“ float ”的字段外,一切都按预期工作。 如果我在“温度”字段的文本框中输入诸如“70.3”的值,则插入的值实际上变为“70.3000030517578”。我还有一个调用更新方法的按钮。如果我将“70.3000030517578”改回“70.3”并将其发送到更新方法,则 70.3 会正确插入到数据库中。 这是我的 SqlCommand 参数代码:

cmd.Parameters.AddWithValue("@temp", listIn[0].Temperature == null ? (object)DBNull.Value : listIn[0].Temperature);

上述行运行后,我在 Debug模式下查看参数,确认Value为70.3。见截图:temp_insert

我将此与更新进行了比较,因为该方法工作正常并且属性变为:temp_update

两个区别在于 DbType 和 SqlDbType。 所以我尝试了下面的行,它没有改变任何东西(仍然添加额外的小数位):

cmd.Parameters.Add("@temp", SqlDbType.Float).Value = listIn[0].Temperature == null ? (object)DBNull.Value : listIn[0].Temperature;

如果我将后端的数据类型更改为 decimal(18,3),则插入方法会正确插入“70.300”。我唯一的选择是使用十进制数据类型而不是 float 吗?如果可能的话,我们更愿意使用 float。欢迎任何想法。我这样做的时间不长,所以如果我的问题不够详细,我深表歉意。

最佳答案

了解 Using decimal, float, and real Data

Approximate numeric data types do not store the exact values specified for many numbers; they store an extremely close approximation of the value. For many applications, the tiny difference between the specified value and the stored approximation is not noticeable. At times, though, the difference becomes noticeable. Because of the approximate nature of the float and real data types, do not use these data types when exact numeric behavior is required, such as in financial applications, in operations involving rounding, or in equality checks. Instead, use the integer, decimal, money, or smallmoney data types.

关于c# - SQL INSERT with ExecuteNonQuery() 插入额外的小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31664100/

相关文章:

sql-server - 如何以与 SQL Server 中相同的顺序将列从 SQL 导入 Excel?

sql - 如何在sql server management studio 2005中检查作业是否被禁用?

c# - 在 C# Web 应用程序中插入查询超时,从 SQL Server Management Studio 运行正常

c# - INotifyPropertyChanged 单例类

c# - 使用 ReSharper 按照与已实现接口(interface)相同的顺序排列成员

java - 我应该在 Hibernate 中批量插入/更新吗?

C#访问静态函数中的非静态成员

c# - 如何在 ControlTemplate 中声明事件处理程序?

android - 如何从 phonegap android 应用程序访问 SQL 服务器数据库?

sql-server - 替换/重命名/修改 SQL Server 中的 JSON 键