简体   繁体   English

SQL Server Round将5解释为更低

[英]Sql server round interpreting 5 as lower

I want to round decimals in sql server 2012 for example: 我想在sql server 2012中四舍五入小数:

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? 我如何使第二个查询返回1.05,如果第5个小数点以下5,则将第三个小数舍入?

Select only 2 digits from the field. 从字段中仅选择2位数字。 This will select high number in 4th position or 5th position 这将选择第4位或第5位的高数字

 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(). 您可以将函数用作round()的第三个参数。 If the function returns 0 then the result is rounded otherwise the result is truncated. 如果函数返回0,则结果将四舍五入,否则结果将被截断。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM