Len function on Float in SQLServer gives wrong length

前端 未结 3 398
小鲜肉
小鲜肉 2020-12-22 03:44

I am using the below query in SQL Server.

declare @dt float
set @dt = 1079938.05
select @dt AS Val,Convert(nvarchar(20),@dt) AS NVal, len(@dt) AS Len
         


        
3条回答
  •  别那么骄傲
    2020-12-22 04:11

    A float in sql server can be 4 or 8 byte. Find details.

    LEN() is a function to measure the lenght of a string. So you want to measure the length of the string representation of the value, not the value itself.

    The shown display value 1.07994e+006 is scientific notation and has 12 characters. Nothing wrong here.

    Your call Convert(nvarchar(20),@dt) calls the CONVERT()-function with the defaul for FLOAT and REAL(Details and other formats here), which is scientific for numbers larger than 6 digits. The same happens implicitly when you call 'len(@dt)'. As the input of LEN() must be a string, the value is converted and then passed to the function.

    What you can do:

    • You might think about a conversion to DECIMAL...

    • Another choice was first to use STR()-function together with RTRIM().

    • One more choice was FORMAT()-function (SQL Server 2012+) .

    Anyway you have to consider, that the text you see is not the real value.

提交回复
热议问题