Why does rounding in SQL Server behave non-intuitively?
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]
Actual:
DecOK DecBad Float NoDiff RoundOK RoundBad
19.85 19.84 19.845 0 19.850 19.84
Expected:
DecOK DecBad Float NoDiff RoundOK RoundBad
19.85 19.85 19.845 0 19.850 19.85
I would expect the value to be the same, regardless of the data type. How can I guarantee accurate results when working with FLOATs? Is the NoDiff
value implicitly converting the second value to a FLOAT which is why the result is exactly 0?