2012-05-17 63 views
0

可能重复:
Truncate (not round) decimal places in SQL Server微软SQL四舍五入到整数,需要1位小数

想不通这一点。我需要返回1个小数位,同时SQL将四舍五入为整数。

我读到整数除以整数给SQL中的整数,但我需要一个截断的小数位在临时表中的输出值。

我不介意35.0回到35,但35.17应该回到35.1。对不起刚刚编辑。需要截断最后一个数字,而不是四舍五入。

create table #blah(output decimal(9,1)) 

DECLARE @a money 
DECLARE @b money 
DECLARE @intinterval decimal(9,1) 

SET @a = 5 
SET @b = 2 
SET @intinterval = (@b/1000.0) * (86400.0/@a) 

INSERT INTO #blah (output) VALUES (@intinterval) 

SELECT * from #blah 

drop table #blah 

上述方程应得到(2-/1000)*(五分之八万六千四)=(0.002 * 17280)= 34.56

的34.56应截断至34.5

+0

@intinterval变量的类型是什么?请修改您的帖子。谢谢 –

+0

@intinterval的声明是什么?这可能是你的问题所在。如果我在'VALUES(@intinterval)'中用'(@b/1000.0)*(86400.0/@a)'代替@intinterval,我会在select语句结果中得到两位小数位数。 –

+0

请参阅此[链接] [1]。你需要转换和使用功能全面 [1]:http://stackoverflow.com/questions/5167299/rounding-decimal-in-sql-server –

回答

1
SET @intinterval = cast(10 * (@b/1000.0) * (86400.0/@a) as int)/10.0 

SET @intinterval = cast(@b * 864.0/@a as int)/10.0 
+0

您的回答是有效的,但史蒂夫卡斯有更好的解决方案。他在评论中回答,而不是回答。感谢您的帮助 – Patriotec

0

Round((@b/1000.0) * (86400.0/@a), 1, 1)怎么样,其中最后1个说法截断,而不是圆。

0

尝试此没有特殊功能...

如果
A = 5然后输出= 34.5(34.56)
一个= 7输出= 24.6(24.69)
一个= 11输出= 15.7( 15.71)

create table #blah(output decimal(9,1)) 
DECLARE @a money 
DECLARE @b money 
DECLARE @intinterval decimal(9,2) 
declare @rounded decimal(9,1)  
declare @diff decimal(9,2) 
declare @finalvalue decimal(9,1) 
SET @a = 5 
SET @b = 2 
SET @intinterval = (@b/1000.0) * (86400.0/@a) 
set @rounded = @intinterval -- gets the rounded value 
set @diff = @intinterval - @rounded -- gets the difference whether to round off or not 
if @diff >= 0   -- if differnce is >= 0 then get the rounded value .. eg. 34.31 = 34.3 
    set @finalvalue = @rounded 
else      -- else subtract 0.1 and get the rounded value e.g. 34.56 - 0.1 = 34.46 -> rounded value of 34.5 
    set @finalvalue = @intinterval - 0.1 
INSERT INTO #blah (output) VALUES (@finalvalue) 
SELECT * from #blah 
drop table #blah 
+0

这比需要的复杂得多。 – MatBailie

+0

不是复杂的队友...只是纯粹的数学。事情是他不想让它四舍五入,功能太贵。 – maSTAShuFu

+0

它比你需要的更复杂,正如其他答案所示。它们给出相同的行为,代码少,CPU时间少,可以更直接地嵌入到SQL查询中。 * [当你声称功能太贵时,我不确定你的意思。例如,ROUND(x,1,1)'既是一种功能,也比CPU更便宜。[*] * – MatBailie