Why does this Sql CAST server (..) round the decimal number to VarChar?

I try to convert some decimalsto varchar, but they get rounded .

Can someone tell me why?

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)

NOTE. Yes, I know that my Lat / Longs is the wrong way. I will switch them soon.

+3
source share
2 answers

This is because your decimal places are not specified with length. They do not store decimals.

Try the following:

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

 SELECT @test, @test2
+6
source

As stated in ck, it is rounded ...

0 ( ), . , 0, numeric_expression .

: ROUND (T-SQL)

+1

Source: https://habr.com/ru/post/1756877/


All Articles