Reputation: 734
I want to convert my decimal SQL query result in percent. Example I have a 0.295333 I want it to be 30% and if I have a 0.090036 I want it to be 9%.
This is what I have so far.
(100 * (sample1/ sample2) ) as 'Percent'
I also tried this one but the problem is result comes with ".00" and I don't know how to remove the decimal.
cast (ROUND(100 * (sample1 / sample2),0) As int ) as 'Percent'
Upvotes: 0
Views: 4117
Reputation: 1298
How does ROUND
work? Does it guarantee return values and if so, how? What is the precedence of the two columns? Does Arithmetic operators
influence the results and how?
I only know what I do not know, and any doubt is worth an investigation.
Since ROUND
always returns the higher precedence, this is not the problem. It is in fact the divide operator ( /
) that may be transforming your values to an integer.
Always verify the variables are consistently of one datatype or CAST
if either unsure or unable to guarantee (such as insufficiently formatted. I.e. DECIMAL(4,2)
instead of required DECIMAL(5,3)
).
DECLARE @Sample1 INT
, @Sample2 DECIMAL(4,2);
SET @Sample1 = 50;
SET @Sample2 =83.11;
SELECT ROUND( 100 * @Sample1 / @Sample2 , 0 )
Returns properly 60.
SELECT ROUND( 100 * @Sample2 / @Sample1 , 0)
Incorrectly turns variables into integers before rounding.
UPDATE This also explains why the decimal remains after ROUND...it is of higher precedence. You can add another cast to transform the non-INT datatype to the preferred format.
SELECT CAST( ROUND( <expression>, <Length>) AS INT)
Note that in answering your question I learned something myself! :)
Hope this helps.
Upvotes: 1
Reputation: 5031
Try with the below script..
cast (100 * Round((sample1 / sample2),2) As int ) as 'Percent'
Upvotes: 2
Reputation: 14381
So as some of the comments pointed out you may need to pay attention to your datatype if one or both of the original columns that you get your decimal from are integer.
One easy way of dealing with that is something like this:
ColA * ColB * 1.0
which will make sure that your integers are treated as decimals
So if you have SQL Server 2012+ you can use Format and not mess with rounding at all. Like this FORMAT(YourDecimal,'#%')
, yep that simple.
;WITH cteValues AS (
SELECT 0.295333 as OriginalValue
UNION ALL
SELECT 0.090036 as OriginalValue
)
SELECT
OriginalValue
,FORMAT(OriginalValue,'#%') as PercentFormat
FROm
cteValues
If you are pre 2012 and do not have format an easy way is to round to the 100th then times by 100 and cast as int CAST(ROUND(YourDecimal,2) * 100 AS INT)
;WITH cteValues AS (
SELECT 0.295333 as OriginalValue
UNION ALL
SELECT 0.090036 as OriginalValue
)
SELECT
OriginalValue
,CAST(ROUND(OriginalValue,2) * 100 AS INT) as PercentInt
FROm
cteValues
Because an INT cannot by definition have decimal places, if you are receiving .00 with the method similar to this or the one you have tried, I would ask the following.
Upvotes: 1