Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert float to varchar in SQL Server

I have a float column with numbers of different length and I'm trying to convert them to varchar.

Some values exceed bigint max size, so I can't do something like this

cast(cast(float_field as bigint) as varchar(100)) 

I've tried using decimal, but numbers aren't of the same size, so this doesn't help too

CONVERT(varchar(100), Cast(float_field as decimal(38, 0))) 

Any help is appreciated.

UPDATE:

Sample value is 2.2000012095022E+26.

like image 804
hgulyan Avatar asked Sep 15 '10 07:09

hgulyan


People also ask

Can we convert varchar to float in SQL?

If you are planning to convert varchar to float you should know that these two data types are not compatible with each other. In the earlier versions of SQL Server you had to use CASE, ISNUMERIC & CONVERT to convert varchar to float but in SQL Server 2012, you can do it with just one function TRY_CONVERT.

Can you convert a float to a string?

We can convert float to String in java using String. valueOf() and Float. toString() methods.

Can we convert float to int in SQL?

Convert Float to Int In this example, we will convert a float data type to integer. In the following query, we will declare a variable that data type is float and then we will use the SQL CONVERT function in order to convert float value to integer so for that we will perform data converting operation.

What SQL function can the analyst use to convert text strings to floats?

Correct. The analyst can use the CAST function to convert text strings to floats.


2 Answers

Try using the STR() function.

SELECT STR(float_field, 25, 5) 

STR() Function


Another note: this pads on the left with spaces. If this is a problem combine with LTRIM:

SELECT LTRIM(STR(float_field, 25, 5)) 
like image 101
codingbadger Avatar answered Sep 21 '22 10:09

codingbadger


The only query bit I found that returns the EXACT same original number is

CONVERT (VARCHAR(50), float_field,128) 

See http://www.connectsql.com/2011/04/normal-0-microsoftinternetexplorer4.html

The other solutions above will sometimes round or add digits at the end

UPDATE: As per comments below and what I can see in https://msdn.microsoft.com/en-us/library/ms187928.aspx:

CONVERT (VARCHAR(50), float_field,3) 

Should be used in new SQL Server versions (Azure SQL Database, and starting in SQL Server 2016 RC3)

like image 38
adinas Avatar answered Sep 22 '22 10:09

adinas