cast or convert a float to nvarchar?

前端 未结 7 1152
醉话见心
醉话见心 2021-02-03 22:02

I need to select from one column of datatype float and insert it in another column as nvarchar.

I tried to cast it: cast([Column_Name] as nvarchar(50))

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-03 22:38

    Do not use floats to store fixed-point, accuracy-required data. This example shows how to convert a float to NVARCHAR(50) properly, while also showing why it is a bad idea to use floats for precision data.

    create table #f ([Column_Name] float)
    insert #f select 9072351234
    insert #f select 907235123400000000000
    
    select
        cast([Column_Name] as nvarchar(50)),
        --cast([Column_Name] as int), Arithmetic overflow
        --cast([Column_Name] as bigint), Arithmetic overflow
        CAST(LTRIM(STR([Column_Name],50)) AS NVARCHAR(50))
    from #f
    

    Output

    9.07235e+009    9072351234
    9.07235e+020    907235123400000010000
    

    You may notice that the 2nd output ends with '10000' even though the data we tried to store in the table ends with '00000'. It is because float datatype has a fixed number of significant figures supported, which doesn't extend that far.

提交回复
热议问题