SQL Server根据数据类型进行舍入

时间:2017-07-07 03:30:31

标签: sql-server sql-server-2008

为什么SQL Server中的舍入行为不直观?

SELECT CAST(     19.845           AS DECIMAL(18, 2)) AS [DecOK]
      ,CAST(CAST(19.845 AS FLOAT) AS DECIMAL(18, 2)) AS [DecBad]
      ,CAST(19.845 AS FLOAT)          AS [Float]
      ,CAST(19.845 AS FLOAT) - 19.845 AS [NoDiff]
      ,ROUND(     19.845          , 2) AS [RoundOK]
      ,ROUND(CAST(19.845 AS FLOAT), 2) AS [RoundBad]

实际值:

DecOK   DecBad  Float   NoDiff  RoundOK RoundBad
19.85   19.84   19.845  0       19.850  19.84

预期:

DecOK   DecBad  Float   NoDiff  RoundOK RoundBad
19.85   19.85   19.845  0       19.850  19.85

无论数据类型如何,我都希望值相同。使用FLOAT时,如何保证准确的结果? NoDiff值是否隐式地将第二个值转换为FLOAT,这就是结果正好为0的原因?

1 个答案:

答案 0 :(得分:0)

Float是近似精度。如果你想要精度,使用DECIMAL或NUMERIC是相同的东西。

这里有很多帖子,但这里很棒。

https://stackoverflow.com/a/7158770