簡體   English   中英

SQL Server Round將5解釋為更低

[英]Sql server round interpreting 5 as lower

我想在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

我如何使第二個查詢返回1.05,如果第5個小數點以下5,則將第三個小數舍入?

從字段中僅選擇2位數字。 這將選擇第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

您可以將函數用作round()的第三個參數。 如果函數返回0,則結果將四舍五入,否則結果將被截斷。

-- Syntax for SQL Server and Azure SQL Database  
ROUND ( numeric_expression , length [ ,function ] )  

SELECT round(1.055,2,1)

編輯:

這是一個完整的例子...

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

結果如下:

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

您可以使用它。 它將為您工作。

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

我會很簡單:

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

嘗試轉換舍入值:

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