Converting a decimal to a integer - sql-server

How can I safely convert the following:
ISNULL(t1.UserPercentage,0) AS UserPercentage
Current the t1.UserPecentage column is a decimal(9,2), I want to convert it to an integer.
Since the value can be NULL, the conversion should be done based on the result of the call to ISNULL correct?

DECLARE #Var DECIMAL(9,2) = 2.67
SELECT CAST(ROUND(#Var,0) AS INT)
This query will keep nulls but If you want to convert NULLS into 0
THEN
SELECT CAST(ROUND(ISNULL(#Var, 0),0) AS INT)
Note
Converting DECIMAL to int without ROUNDing it will give you a bit less
accurate result then if you ROUND it to zero before you cast it as
int.
Direct conversion into INT will simply truncate any decimals but if
you ROUND it to zero 1st and then CAST as int , it will give you more
realistic results.
Example
DECLARE #Var DECIMAL(9,2) = 2.67
SELECT CAST(#Var AS INT)
This will return 2, but basic rules of mathematics says this value is 3 if it is rounded to a whole number.
DECLARE #Var DECIMAL(9,2) = 2.67
SELECT CAST(ROUND(#Var,0) AS INT)
This query will return 3. More accurate then just converting it to INT.

If your desired result is a simple truncation of the decimal points, using FLOOR is your best option. At first glance, it would be more obvious to other people what you're trying to do.
ISNULL(FLOOR(t1.UserPercentage), 0) AS UserPercentage
Examples:
SELECT FLOOR(1.1), FLOOR(1.9)
-- Result is a simple truncation of the decimal points. (=1)

declare #val decimal(9,2) =43.44
select convert(int, #val)
or
select cast(#val as int)

Related

Conversion failed when converting the nvarchar to int bigint

Hopefully this is quite straight forward. I am trying to convert a column to int so I can sum on it.
SELECT (cast(RTRIM(pricing_prices)as int)) FROM returnxx where RMAid= '5'
errors
Conversion failed when converting the nvarchar value
'9.8000000000000007' to data type int.
If I try bigint I get another error
Error converting data type nvarchar to bigint.
First convert into Numeric and then INT.
Try this:
DECLARE #Var varchar(100)='9.8000000000000007'
SELECT CAST(CAST(#Var AS NUMERIC(35,16)) AS INT)
Result:
9
If you want ROUND value, just convert into Numeric:
SELECT CAST(#Var AS NUMERIC)
Result:
10
If you want DECIMAL value, just convert into Numeric:
SELECT CAST(#Var AS NUMERIC(8,2))
Result:
9.80
I have this problem in the past. i was able to resolve it by casting the column to decimal first then cast it to an Integer. You can cast it to any decimal of your choice
DECLARE #pricing_prices NVARCHAR(20)='9.8000000000000007' AS pricing_prices
SELECT CAST(CAST(#pricing_prices AS DECIMAL(9,2)) AS INT)
Output
pricing_prices
9

MS SQL change Cast count VarChar to %

In the last line of the code I have listed below, The current result is blank because the result is less than 1. I need the results to display as a percentage but I'm not sure how. Any suggestions are greatly appreciated?
SELECT
'1,*'+char(13)+char(10)
+'80,1006058'+char(13)+char(10)
+'100,10'+char(13)+char(10)
+'2405,'+cast(count(distinct adt.PAT_ENC_CSN_ID) / 420 as varchar(18))+char(13)+char(10) --Census events --as varchar(10)
The issue is that your count(distinct adt.PAT_ENC_CSN_ID) returns an integer value and then you divide by 420. Another integer.
If you cast the count distinct as a decimal or float, this should solve your issue. CAST(COUNT(DISTINCT adt.PAT_ENC_CSN_ID) AS FLOAT).
SELECT
'1,*'+char(13)+char(10)
+'80,1006058'+char(13)+char(10)
+'100,10'+char(13)+char(10)
+'2405,'+cast( cast(count(distinct adt.PAT_ENC_CSN_ID) AS FLOAT) / cast(420 AS FLOAT) as varchar(18))+char(13)+char(10) --Census events --as varchar(10)
You should cast() your numbers as float otherwise they are considered as integers and you don't have decimals in your division because the result is also considered integer
Just replace this part
cast(count(distinct adt.PAT_ENC_CSN_ID) / 420 as varchar(18))
with
cast(count(distinct adt.PAT_ENC_CSN_ID) / 420.00 as varchar(18))
Note that all we did was turn 420 to 420.00 to suggest SQL to retain decimal part and not treat the result as integer.
As count return integer values and integer/integer is an integer but integer/decimal is decimal

How to trim all the zeros value after decimal of the rounded value

declare #v nvarchar(50) = '21.89777777777777777777777777'
select convert(decimal(18,8),round(#v,3))
Unable to truncate the decimal values after rounded. eg in above question, it returns 21.8980000.
The resulting output must be like
21.898 when rounded by select convert(decimal(18,8),round(#v,3))
and 21.8988 when rounded by round(#v,4)
I have created an stored procedure from where i gets the round value. and it must trim the leading zeros after rounded. and It must be dynamic instead of changing the precision everytime
use a different precision for the decimal
declare #v nvarchar(50) = '21.89777777777777777777777777'
select convert(decimal(18,3),round(#v,3))
SQLFiddle demo
The value is the same, regardless if it's 21.8980000 or 21.898. It's the format that is different.
You should be formatting the value on the client, rather then on SQL Server.
Float will do your job
declare #v nvarchar(50) = '21.89777777777777777777777777'
select convert(float,round(#v,3))

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.

Decimal values in SQL for dividing results

In SQL, I have col1 and col2. Both are integers.
I want to do like:
select col1/col2 from tbl1
I get the result 1 where col1=3 and col2=2
The result I want is 1.1
I put round(col1/col2,2). The result is still 1.
I put decimal(col1/col2,2). The decimal is not built in function.
How can I do exactly to get 1.1?
Just another approach:
SELECT col1 * 1.0 / col2 FROM tbl1
Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.
A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:
SELECT col1 * 1. / col2 FROM tbl1
The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).
Principal advantage: less wordy than other approaches.
You will need to cast or convert the values to decimal before division. Take a look at this
http://msdn.microsoft.com/en-us/library/aa226054.aspx
For example
DECLARE #num1 int = 3 DECLARE #num2 int = 2
SELECT #num1/#num2
SELECT #num1/CONVERT(decimal(4,2), #num2)
The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000
SELECT CAST (col1 as float) / col2 FROM tbl1
One cast should work. ("Less is more.")
From Books Online:
Returns the data type of the argument with the higher precedence. For more information about data type precedence, see Data Type Precedence (Transact-SQL).
If an integer dividend is divided by an integer divisor, the result is an integer that has any fractional part of the result truncated
CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)
There may be other ways to get your desired result.
Declare #a int
Declare #b int
SET #a = 3
SET #b=2
SELECT cast((cast(#a as float)/ cast(#b as float)) as float)
just convert denominator to decimal before division e.g
select col1 / CONVERT(decimal(4,2), col2) from tbl1

Resources