To convert float value to string - sql-server

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.

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.

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)

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));

Related

T-SQL: Convert money to float

How can I convert (money/int)*100 to a float datatype?
a.ResidualValue is of type money, while ListPriceCar is of type int.
The following outputs a number with a comma as the decimal separator, so I presume it is still a money field, and not a float as I wish:
CONVERT(float, CONVERT(float, REPLACE(CONVERT(nvarchar(10), a.ResidualValue), ',', '.'))/ListPriceCar)*100 AS 'Residual value %'
Result: 62,825
What is issue with simple cast as below:
DECLARE #money AS money
SET #money = $2345234.35
SELECT #money, CAST(#money AS float)
What's the value of ResidualValue? If ResidualValue contains a comma, then comma is your decimal char. You shouldn't convert it into a point then. You can divide a money value by an int value.
declare #a money = 10.5;
declare #b int = 20;
select (#a / #b) * 100
select cast((#a / #b) * 100 as float)
In your example, the result was already given as an float. You can test this by running the following example code.
--INPUT VARIABLES
declare #ResidualValue money = 5000.54
declare #ListPriceCar int = 15000
--OUTPUT VARIABLE
declare #ResultCalculation as sql_variant;
--CALCULATION
set #ResultCalculation = CONVERT(float, CONVERT(float, REPLACE(CONVERT(nvarchar(10), #ResidualValue), ',', '.'))/#ListPriceCar)*100
--GET INFORMATION ON THE OUTPUT VARIABLE
select sql_variant_property(#ResultCalculation,'BaseType') AS 'Base Type',
sql_variant_property(#ResultCalculation,'Precision') AS 'Precision',
sql_variant_property(#ResultCalculation,'Scale') AS 'Scale',
sql_variant_property(#ResultCalculation,'TotalBytes') AS 'TotalBytes',
sql_variant_property(#ResultCalculation,'Collation') AS 'Collation',
sql_variant_property(#ResultCalculation,'MaxLength') AS 'MaxLength';
There is an easier way to calculate your answer:
CAST(#ResidualValue/#ListPriceCar * 100 as float)

Elimanating zero decimals from Computed Fields

i have the computed field in TSQl which computed size field but how can i get ride of Zero from decimals
forexample
RIM DIAMETER = 12.0
RIM WIDTH= 10.5
the computed field SIZEdisplayed as 12.0X10.50 i want the result to be displayed as 12X10.5
ALTER TABLE dbo.[RIMS] ADD [SIZEtst] AS (
CASE
WHEN CONVERT (VARCHAR(50), [RIM DIAMETER],0) IS NULL THEN ''
ELSE CONVERT (VARCHAR(50), [RIM DIAMETER],0)
end +
'X'+
CASE
WHEN CONVERT (VARCHAR(50), [RIM WIDTH],0) IS NULL THEN ''
ELSE CONVERT (VARCHAR(50), [RIM WIDTH],0)
end
Consider Format()
Declare #D decimal(10,2) = 12.0
Declare #W decimal(10,2) = 10.5
Select concat(format(#D,'0.#'),'X',format(#W,'0.#'))
Returns
12X10.5
Or the implicit conversion using float
Declare #D float = 12.0
Declare #W float = 10.5
Select concat(#D,'X',#W)
This was intended as a demonstration of format function and/or the implicit conversion
[SizeTst] AS (concat(CONVERT([float],[RIM Diameter]),'X',CONVERT([float],[RIM Width])))
or
[SizeTst] AS (concat(format([RIM Diameter],'0.#'),'X',format([RIM Width],'0.#')))
-- you can define table like this
create table [RIMS](
[RIM DIAMETER] float,
[RIM WIDTH] float
)

Error when converting float to datetime

I am trying to convert a float in the format yyyymmdd to datetime. According to this the correct style code for that format is 112.
Code:
select
convert(datetime,cast(myDate as numeric),112)
from MyTable
Error:
Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type datetime.
I get the same error without the cast as numeric part. I've been looking around for a couple hours, but I haven't been able to find anything that fixes this. If you know a better way to convert the float to a datetime I would be open to that idea.
Thank you for your help.
EDIT
Here is the working code:
SELECT
case when isdate(CAST(CAST(myDate AS INT) AS VARCHAR(8))) = 1
then CAST(CAST(CAST(myDate AS INT) AS VARCHAR(8)) AS DATETIME)
end
from MyTable
I wrapped it in the isdate because there were a few invalid dates in there. Thanks to Matt for the help.
EDIT2
Better version:
SELECT
TRY_CAST(CAST(CAST(myDate AS INT) AS VARCHAR(8)) AS DATETIME)
FROM MyTable
First you must convert the FLOAT to a VARCHAR. And since FLOAT has a number of decimal points, it must first be converted to an INT.
DECLARE #myDate FLOAT
SET #myDate = 20140721
SELECT CAST(CAST(#myDate AS INT) AS VARCHAR(8))
--20140721
Then you can convert the VARCHAR to DATE or DATETIME format.
DECLARE #myDate FLOAT
SET #myDate = 20140721
SELECT CAST(CAST(CAST(#myDate AS INT) AS VARCHAR(8)) AS DATE)
--2014-07-21

mssql convert varchar to float

I have a field value productlength of 0.123. This is from a view and has a data type of varchar.
I need to convert it to a float or numeric value so as o perform math comparisons.
convert(float,productlength)
and
cast(productlength as float) both do not work.
error varchar cant be converted to float or somethiing liek that.
From what I have read varchar can simply not be converted to a numeric string?
Any clever ways around this?
You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:
declare #thing varchar(100)
select #thing = '122.332'
--This returns 1 since it is numeric.
select isnumeric(#thing)
--This converts just fine.
select convert(float,#thing)
select #thing = '122.332.'
--This returns 0 since it is not numeric.
select isnumeric(#thing)
--This convert throws.
select convert(float,#thing)
Use
Try_convert(float,[Value])
See
https://raresql.com/2013/04/26/sql-server-how-to-convert-varchar-to-float/
DECLARE #INPUT VARCHAR(5) = '0.12',#INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, #INPUT) YOUR_QUERY ,
case when isnumeric(#INPUT_1)=1 THEN CONVERT(float, #INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE #INPUT VARCHAR(5) = '0.12',#INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, #INPUT) YOUR_QUERY ,
case when isnumeric(#INPUT_1)=1 THEN CONVERT(float, #INPUT_1) ELSE **#INPUT_1** END AS YOUR_QUERY_ANSWERED
as #INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.

Why is casting from float to varchar being rounded in SQL Server?

The following SQL,
declare #a as float, #b as float
select #a=1.353954 , #b=1.353956
select
CAST(#a as VARCHAR(40)) AS a_float_to_varchar ,
CAST(#b as VARCHAR(40)) AS b_float_to_varchar
results in
a_float_to_varchar b_float_to_varchar
---------------------------------------- ----------------------------------------
1.35395 1.35396
based on 'float' and 'real' (Transact-SQL).
Float has a precision of 15 digits, so I am not sure why the number is being rounded when converted to varchar.
Also from your link (it's actually the first line):
Approximate-number data types...
If you want exact precision, don't use float.
That being said, there is a function STR() specifically for converting float to a character data type.
Cast to decimal before casting to varchar:
declare #a as float, #b as float
select #a=1.353954 , #b=1.353956
select
CAST(CAST(#a AS DECIMAL(38,18)) as VARCHAR(40)) AS a_float_to_varchar ,
CAST(CAST(#b AS DECIMAL(38,18)) as VARCHAR(40)) AS b_float_to_varchar
You can specify style to include more digits.
declare #gg float
set #gg = 124.323125453
SELECT #gg,Convert(varchar, #gg,128)
For newer versions of SQL Server, use SELECT #gg,Convert(varchar, #gg,3)
returns
124.323125453 124.323125453
Reference: CAST and CONVERT (Transact-SQL)
Or with STR():
declare #gg float
set #gg = 124.323124354234524
SELECT #gg,str(#gg,16,15)
It should give you all the possible digits. 16 is the total possible length (includes period) while 15 places after the decimal is possible (actually 0.2323... the 0 count toward length, so the length needs to be 17 if all numbers are less that 1). STR(), however, pads the results with leading spaces and trailing 0.

Resources