Aparanjit
Aparanjit

Reputation: 41

To convert float value to string

I am using two columns which have Date and float values, now I need to combine both the columns as a single string. For date I am able to convert it to string. But for the float values it is rounding up the decimal value which should not be the case.

For example my float value is 204.8 and date id 2014-11-11. Now when I combine as string it should result as '2014-11-11 204.8' But it is showing me as '2014-11-11 204' when I convert float value. I am using this query,

DECLARE @myDateTime DATETIME
DECLARE @StandardCost INT
SET @myDateTime = '2011-12-24 00:00:00.000'
SET @StandardCost = 204.8
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)+ ' ' + CAST(@StandardCost AS VARCHAR(MAX))

Result: 2011-12-24 204

Can anyone help me in getting exact float value with decimals as string.

Upvotes: 0

Views: 1893

Answers (3)

Sean Lange
Sean Lange

Reputation: 33581

You have @StandardCost defined as an int. It will not hold the decimal portion. Change that to a numeric or some other datatype that will support decimal places.

Upvotes: 5

Dbloch
Dbloch

Reputation: 2376

As @Sean Lange said change the INT variable to a FLOAT

DECLARE @myDateTime DATETIME
DECLARE @standardcost FLOAT;   -- <-------- Changed INT to FLOAT
SET @mydatetime = '2011-12-24 00:00:00.000';
SET @standardcost = 204.8;
SELECT LEFT(CONVERT(VARCHAR, @mydatetime, 111), 10) + ' ' + CAST(@standardcost AS VARCHAR(MAX));

Upvotes: -1

Jacky
Jacky

Reputation: 3259

First, you need to declare its as FLOAT, instead of INT

Then, you can try using STR() function

DECLARE @StandardCost FLOAT
SET @StandardCost = 204.8
SELECT STR(@StandardCost,10,1)

Upvotes: 0

Related Questions