How to round a number upto n decimal places in sql server - sql

I have column in table which I want to round upto some decimal places.
Which is stored in some other table.
Actually my data is stored as 8 decimal places, but based on user preference, I need to show upto that decimal place.
Column datatype is numeric(19,8)
I have procedure which is returning all rows. So At that time only I want to round my column up to specified decimal decimal
Want to do something like
declare #i int = 2
Begin
select cast (12533333.193 as numeric(38,#i))
end
how to achieve this?
Please suggest

This is the MOST easy of all
Before starting I want to tell that this works only for float type (Yes! you need to convert your decimals / numerics to float!). Syntax wise it is Most Readable as well!
select round(cast(65.456 as float),2) (This will round off to 2 decimal places)
select round(cast(65.456 as float),1) (This will round off to 1 decimal places)
select round(cast(65.456 as float),0) (This will round off to 0 decimal places)
See the snapshot below

You can just use the ROUND function for sql-server
DECLARE #i int = 2
BEGIN
SELECT ROUND(val,#i)
FROM mytable
END
SQLFIDDLE

you can cast to number with 2 decimal after round up in query,
or when you display at report or system
DECLARE #i int = 2
BEGIN
SELECT
cast(
ROUND(val,#i)
as decimal(10,2)
)
FROM mytable
END

Related

How to round multiple numeric columns to 2 digits in sql?

Say if I need to round multiple numbers to 2 digits now, but I don't want to repeat using round(..., 2) or format(...).
Is there any method to set up the float numbers with 2 digits globally?
select cast(float_column as decimal(10,2))
from your_table
Declare the column or variable of type numeric(18, 2)
You can also use with the CONVERT function
select CONVERT(numeric(18, 2) , 5.54722)

Remove decimal using SQL query

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'
Try with the below script..
cast (100 * Round((sample1 / sample2),2) As int ) as 'Percent'
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.
Are you combining (multiplying etc.) the value after casting with another column or value that may be decimal, numeric, or float?
Are you looking at the query results in a program outside of SSMS that could be formatting the results automatically, e.g. Excel, Access?
Address your assumptions first.
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.
THE DIVIDEND OPERATOR
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.
The reason is that DIVIDE - MSDN in SQL may return the higher precedence, but any dividend that is an integer returns another integer.
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.

How to format % and in 2 decimal points?

How do I code format the return data in 2 decimals and with percentage format like 100.00% or 67.39% instead of 100.000000 or 67.391304?
SUM(qa.scripting1+qa.conduct1+qa.conduct2+qa.conduct3)*100.0/46 as 'C%'
I tried ROUND() but I got the error stating that the round function requires 2 to 3 arguments?
ROUND(SUM(qa.scripting1+qa.conduct1+qa.conduct2+qa.conduct3)*100.0/46) as 'C%'
Thanks!
You can convert to a decimal your original value:
CONVERT(VARCHAR(20), CONVERT(DECIMAL(18,2), SUM(qa.scripting1+qa.conduct1+qa.conduct2+qa.conduct3)*100.0/46) ) + '%' as 'C%'
The first number in the decimal represents the number of digits in the number including decimal places, and the second number represents the number of decimal places.
You should pass number of decimals in second parameter to round function. For formating you can cast number to money and then cast to varchar:
select cast(cast(ROUND(SUM(123.12321)*100.0/46, 2) as money) as varchar) + '%'
Using Round and Cast will work. First round to 2 decimal places then convert to a decimal with 2 places to truncate the excess zeros.
select cast(Round(yourValue, 2) as decimal(18,2))
Sql Fiddle
You can use Format function
select FORMAT(100.0000, 'N' , 'en-us')
returns 100.00
and
select FORMAT(67.391304, 'N' , 'en-us')
returns 67.39
EDIT
In version below 2012 you can do this
SELECT CAST(67.391304 AS NUMERIC(10, 2))
returns 67.39
You can just do:
select FORMAT(0.391304, '##0.00%')
But keep in mind that it implicitly multiplies by 100, so the above will display as 39.13%.

T-SQL Conditional logic based on Thousandth ( .00X) decimal point

I am trying to use either Round or Ceiling method based on Thousandth decimal number.
How do I write condition in the T-SQL stored procedure?
Thanks in advance!
Example:
If I have this number:
1,793.5123611111
I would like to use Round( Variable ,2,1) so that it becomes 1,793.51
So that thousandth decimal does not round off.
If I have this number:
11,80620619333
I would like to use ceiling(Variable *100) / 100 so that it becomes 11,806.21
So that thousandth decimal rounds off.
Thanks.
What is the current data type? VARCHAR?
You may try this
DECLARE #a VARCHAR(100) = '11,806.20619333'
PRINT CONVERT(VARCHAR(100),CAST(#a AS MONEY),1)
Use ROUND() without a third argument. When the third argument is not specified, it defaults to 0, which means rounding (any other value means truncating):
SELECT ROUND(Value, 2)
FROM (
SELECT 1793.5123611111
UNION ALL
SELECT 11806.20619333
) AS s (Value)
;
The above will yield these results:
--------
1793.51
11806.21

Sql query to convert nvarchar to int

I have to query for total amount of a column using an aggregate function. The column data type is NVARCHAR(MAX). How can I convert it to Integer?
I have tried this:
SELECT SUM(CAST(amount AS INT)),
branch
FROM tblproducts
WHERE id = 4
GROUP BY branch
...but I'm getting:
Conversion failed when converting the nvarchar value '3600.00' to data type int.
3600.00 is not integer so CAST via float first
sum(CAST(CAST(amount AS float) AS INT))
Edit:
Why float?
no idea of precision or scale across all rows: float is the lesser evil perhaps
empty string will cast to zero for float, fails on decimal
float accepts stuff like 5E-02, fails on decimal
In addition to gbn's answer, you need to protect against non-numeric cases:
sum(CASE WHEN ISNUMERIC(Amount)=1 THEN CAST(CAST(amount AS float) AS INT)END )
SELECT sum(Try_Parse(amount as Int Using 'en-US')),
branch
FROM tblproducts
WHERE id = 4
GROUP BY branch