I want to round decimals in sql server 2012 for example:
Select ROUND(1.056,2) -- returns 1.06
Select ROUND(1.055,2) -- returns 1.06
Select ROUND(1.054,2) -- returns 1.05
How can I make the second query returns 1.05 rounding the third decimal if 5 to lower?
Select only 2 digits from the field. This will select high number in 4th position or 5th position
select
case when right ( 'colvalue',1) > right (SUBSTRING('colValue',1,4),1)
then ROUND('colvalue',2)
else ROUND (LEFT ( 'colvalue',4) ,2) end RoundValue
You can use a function as third argument of round(). If the function returns 0 then the result is rounded otherwise the result is truncated.
-- Syntax for SQL Server and Azure SQL Database
ROUND ( numeric_expression , length [ ,function ] )
SELECT round(1.055,2,1)
Edit:
Here is a complete example...
create table test
(
n decimal(10,7) not null
)
GO
insert into test (n)
values
(1.050),
(1.051),
(1.052),
(1.053),
(1.054),
(1.055),
(1.056),
(1.057),
(1.058),
(1.059)
GO
select n, round(n,2,iif(n - round(n,2,1)>.005,0,1)) as rounded from test
GO
Here is the result :
n rounded
1.0500000 1.0500000
1.0510000 1.0500000
1.0520000 1.0500000
1.0530000 1.0500000
1.0540000 1.0500000
1.0550000 1.0500000
1.0560000 1.0600000
1.0570000 1.0600000
1.0580000 1.0600000
1.0590000 1.0600000
You can use this. It will work for you.
DECLARE @test decimal(10,3) = 1.055
SELECT CASE WHEN round(@test,3,1) - round(@test,2,1) = 0.005 THEN round(@test,2,1) ELSE round(@test,2) END
I would go with simple:
DECLARE @test nvarchar(10)
DECLARE @test_string nvarchar(10)
SET @test_string='1.055'
-- SET @test_string='1.056' -- is here to test
SET @test = SUBSTRING(@test_string,5,5)
IF @test=5
BEGIN
SELECT ROUND (LEFT(@test_string,4),2)
END
ELSE
BEGIN
SELECT ROUND (@test_string,2)
END
Try casting the rounded value:
Select CAST(ROUND(1.056,2) AS NUMERIC(10,2)) -- returns 1.06
Select CAST(ROUND(1.055,2) AS NUMERIC(10,2)) -- returns 1.06
Select CAST(ROUND(1.054,2) AS NUMERIC(10,2)) -- returns 1.05
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.