convert float into varchar in SQL server without scientific notation and trimming decimals.
for Ex:
i have float value 1000.2324422, then it
STR function works nice. I had float coming back after doing some calculations and needed to change to VARCHAR, but was getting scientific notation randonly as well. I made this transformation after all the calcs
ltrim(rtrim(str(someField)))
This works:
Suppose
dbo.AsDesignedBites.XN1E1 = 4016519.564`
For the following string:
'POLYGON(('+STR(dbo.AsDesignedBites.XN1E1, 11, 3)+'...
Neither str()
or cast(float as nvarchar(18))
worked for me.
What did end up working was converting to an int and then converting to an nvarchar like so:
convert(nvarchar(18),convert(bigint,float))
Casting or converting to VARCHAR(MAX)
or anything else did not work for me using large integers (in float fields) such as 167382981, which always came out '1.67383e+008'.
What did work was STR()
.
You will have to test your data VERY well. This can get messy. Here is an example of results simply by multiplying the value by 10. Run this to see what happens. On my SQL Server 2017 box, at the 3rd query I get a bunch of *********. If you CAST as BIGINT it should work every time. But if you don't and don't test enough data you could run into problems later on, so don't get sucked into thinking it will work on all of your data unless you test the maximum expected value.
Declare @Floater AS FLOAT =100000003.141592653
SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(@Floater,0)),
STR(@Floater)
SET @Floater =@Floater *10
SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(@Floater,0)),
STR(@Floater)
SET @Floater =@Floater *100
SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ),
CONVERT(VARCHAR(100),ROUND(@Floater,0)),
STR(@Floater)
There are quite a few answers but none of them was complete enough to accommodate the scenario of converting FLOAT
into NVARCHAR
, so here we are.
This is what we ended up with:
DECLARE @f1 FLOAT = 4000000
DECLARE @f2 FLOAT = 4000000.43
SELECT TRIM('.' FROM TRIM(' 0' FROM STR(@f1, 30, 2))),
TRIM('.' FROM TRIM(' 0' FROM STR(@f2, 30, 2)))
SELECT CAST(@f1 AS NVARCHAR),
CAST(@f2 AS NVARCHAR)
Output:
------------------------------ ------------------------------
4000000 4000000.43
(1 row affected)
------------------------------ ------------------------------
4e+006 4e+006
(1 row affected)
In our scenario the FLOAT
was a dollar amount to 2 decimal point was sufficient, but you can easily increase it to your needs.
In addition, we needed to trim ".00" for round numbers.