将浮点值插入SQL Server表 [英] Insert float value into SQL Server table

查看:215
本文介绍了将浮点值插入SQL Server表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点值,我正在尝试使用以下代码插入SQL Server表中:

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(); 
    }
}

这是存储过程:

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

问题是我有这个浮点数值,例如 3.7723 并在数据库中为 3.77230000495911

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

任何想法问题是?我想在点后仅插入4位数字

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

推荐答案

您需要使用十进制(18,4)数据类型

十进制/数字与浮点数之间的基本区别:

The basic difference between Decimal/Numeric and Float :


浮点数是近似数字数据类型,这意味着不能准确表示数据类型范围内的所有值
。十进制/数字是
固定精度数据类型,这意味着数据
类型reane中的所有值都可以精确地表示为精度和小数位数。

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.

从十进制或数值转换为浮点数可能会导致精度损失。对于十进制或数字数据类型,SQL Server将精度和小数位的每种特定组合视为不同的数据类型。 DECIMAL(2,2)和DECIMAL(2,4)是不同的数据类型。这意味着11.22和11.2222是不同的类型,尽管float并非如此。对于FLOAT(6),11.22和11.2222是相同的数据类型。

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.

这篇关于将浮点值插入SQL Server表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆