cast or convert a float to nvarchar?
Solution 1:
Check STR. You need something like SELECT STR([Column_Name],10,0)
** This is SQL Server solution, for other servers check their docs.
Solution 2:
If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.
So instead of:
select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009
You would use:
select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890
In these examples the innermost cast(1234567890 as float)
is used in place of selecting a value from the appropriate column.
I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?
select cast(0100884555 as float)
100884555
Whoops! We just stored an incorrect phone number...
Solution 3:
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.