【问题标题】:Microsoft SQL rounding off to whole number, need to 1 decimal place [duplicate]Microsoft SQL 四舍五入为整数,需要保留 1 位小数 [重复]
【发布时间】:2012-05-17 03:15:44
【问题描述】:

可能重复:
Truncate (not round) decimal places in SQL Server

想不通。当 SQL 舍入为整数时,我需要返回 1 个小数位。

我读到整数除以整数在 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) * (86400 / 5) = (0.002 * 17280) = 34.56

34.56 应截断为 34.5

【问题讨论】:

  • @intinterval 变量的类型是什么?请编辑您的帖子。谢谢
  • @intinterval 的声明是什么?这可能就是你的问题所在。如果我用(@b / 1000.0) * (86400.0 / @a) 替换VALUES (@intinterval) 中的@intinterval,我会在select 语句结果中得到两位小数。
  • 参考这个[link][1]。需要投和使用round函数[1]:stackoverflow.com/questions/5167299/…
  • 添加了@intinterval decimal(9,1)
  • Patriotec:你需要四舍五入到小数点后 1 位,而不是 3 位。试试 round(round((@mnyminbid / 1000.00) * (86400.00 / @mnybudget),1, 1). 这是一个计算的 SQL Fiddle:sqlfiddle.com/#!3/c368d/5。注意 ROUND 有三个参数。第二个 1 是小数位数。ROUND 中的最后一个 1 表示截断而不是向上或向下舍入,以更近者为准。

标签: sql database sql-server-2008


【解决方案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

【讨论】:

  • 你的答案是可行的,但史蒂夫卡斯有更好的解决方案。他在评论中回答,而不是在答案中。感谢您的帮助
【解决方案2】:

Round((@b / 1000.0) * (86400.0 / @a), 1, 1) 怎么样,最后 1 句话是截断而不是舍入。

【讨论】:

    【解决方案3】:

    试试这个没有特殊功能...

    如果
    a = 5 然后输出 = 34.5 (34.56)
    a = 7 输出 = 24.6 (24.69)
    a = 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  
    

    【讨论】:

    • 这比它需要的复杂得多。
    • 不是复杂的伙伴...只是纯粹的数学。问题是他不希望它被四舍五入并且功能太昂贵。
    • 它比它需要的更复杂,如您之前的其他答案所示。它们以更少的代码和更少的 cpu 时间提供相同的行为,并且可以更直接地嵌入到 sql 查询中。 [当您断言功能太昂贵时,我不确定您的意思是什么?例如,ROUND(x, 1, 1) 既是一个函数,而且在 CPU 方面比这段代码更便宜...]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多