为什么这个Sql Server CAST(..)将十进制舍入为VarChar?

Pur*_*ome 3 sql-server casting rounding-error sql-server-2008

我试图将一些decimalsvarchar,但是之后就被四舍五入.

有人可以告诉我为什么吗?

declare @UpperLeftLatitude DECIMAL,
    @UpperLeftLongitude DECIMAL,
    @BottomRightLatitude DECIMAL,
    @BottomRightLongitude DECIMAL

SET @UpperLeftLatitude = 38.663
SET @UpperLeftLongitude = -122.857
SET @BottomRightLatitude = 37.795
SET @BottomRightLongitude = -121.219


DECLARE @SearchRectangleString VARCHAR(MAX);
SET @SearchRectangleString = 'POLYGON((' + CONVERT(VARCHAR(50), @UpperLeftLatitude) + ' ' + CAST(@UpperLeftLongitude AS VARCHAR(50)) + ',' 
    + CAST(@BottomRightLatitude AS VARCHAR(50)) + ' ' + CAST(@UpperLeftLongitude AS VARCHAR(50)) + ',' 
    + CAST(@BottomRightLatitude AS VARCHAR(50)) + ' ' + CAST(@BottomRightLongitude AS VARCHAR(50)) + ',' 
    + CAST(@UpperLeftLatitude AS VARCHAR(50)) + ' ' + CAST(@BottomRightLongitude AS VARCHAR(50)) + ',' 
    + CAST(@UpperLeftLatitude AS VARCHAR(50)) + ' ' + CAST(@UpperLeftLongitude AS VARCHAR(50)) + '))';

    SELECT @SearchRectangleString

-------------------
POLYGON((39 -123,38 -123,38 -121,39 -121,39 -123))

(1 row(s) affected)
Run Code Online (Sandbox Code Playgroud)

注意:是的,我知道我的Lat/Longs是错误的.我很快就会转换它们.

cjk*_*cjk 6

这是因为您的小数未指定长度.它们不存储任何小数位.

请尝试以下方法:

 DECLARE @test DECIMAL, @test2 DECIMAL(8,4)
 SET @test = 12.3456
 SET @test2 = 12.3456

 SELECT @test, @test2
Run Code Online (Sandbox Code Playgroud)