Insert float value into SQL Server table

时光毁灭记忆、已成空白 提交于 2019-12-12 02:53:21

问题


I have a float value that I'm trying to insert into a SQL Server table with this code:

SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand("AddNewValue", connection);

command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("value", SqlDbType.Float).Value = value;

try
{
    connection.Open();
    command.ExecuteNonQuery();
}
finally
{
    if (connection.State == ConnectionState.Open) 
    { 
        connection.Close(); 
    }
}

And this is the stored procedure:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[AddNewValue]
     (@value float)
AS
    INSERT INTO MYTable (value, date) 
    VALUES (@value, GETDATE())
GO

The problem is that I have this float number value for example 3.7723 and in the database, it's 3.77230000495911.

Any idea what the problem is? I want to insert the value with only 4 digits after the dot


回答1:


You need to use the Decimal (18,4) Datatype

The basic difference between Decimal/Numeric and Float :

Float is Approximate-number data type, which means that not all values in the data type range can be represented exactly. Decimal/Numeric is Fixed-Precision data type, which means that all the values in the data type reane can be represented exactly with precision and scale.

Converting from Decimal or Numeric to float can cause some loss of precision. For the Decimal or Numeric data types, SQL Server considers each specific combination of precision and scale as a different data type. DECIMAL(2,2) and DECIMAL(2,4) are different data types. This means that 11.22 and 11.2222 are different types though this is not the case for float. For FLOAT(6) 11.22 and 11.2222 are same data types.




回答2:


This is a standard behavior of floats, due to the way they store values.

You have two options here, depending on your requirements:

  • Use a decimal with the desired precision instead of a float (both in the DB and the client side).
  • Store the value as a float, but truncate it to the desired precision when you want to display it.


来源:https://stackoverflow.com/questions/36595798/insert-float-value-into-sql-server-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!