谁能解释以下代码的结果?我认为这是SQL SERVER 2014中的错误
DECLARE @x float
SET @x=58.415
SELECT ROUND(58.415,2), ROUND(@x,2)
谁能解释以下代码的结果?我认为这是SQL SERVER 2014中的错误
DECLARE @x float
SET @x=58.415
SELECT ROUND(58.415,2), ROUND(@x,2)
因为第一个参数存储为十进制(5,3):
EXEC sp_describe_first_result_set N'SELECT 58.415 x', null, 0;
您有两个不同的代码:
DECLARE @x float
SET @x=58.415
SELECT ROUND(58.415,2), ROUND(@x,2)
GO
DECLARE @x decimal(19,3)
SET @x=58.415
SELECT ROUND(58.415,2), ROUND(@x,2)
GO
基本上,浮点数是
与浮点数字一起使用的近似数字数据类型 数据。浮点数据是近似值;因此,并非所有的值 数据类型范围可以准确表示。
您所看到的解释是,浮点算术在SQL Server(或任何其他数据库或编程语言)中并不准确。这是实际发生的情况,其中显示了“真实”值以供说明:
SELECT
ROUND(58.415, 2), -- rounds UP to 58.420
ROUND(58.4149999999999, 2) -- rounds DOWN to 58.41
这里的问题是当您进行以下变量分配时:
DECLARE @x float
SET @x = 58.415
internally, SQL Server actually stored the value as an approximation, something like 58.41499999999
. Then, when rounding to two decimal places, you were left with 58.41
.
In general, if you require exact precision, you should use an exact type. In this case, DECIMAL(10,3)
would work.