如何舍入小数?

时间:2015-07-07 00:09:48

标签: stored-procedures

我在用十进制数字舍入数字时遇到问题

搜索结果我只得到以下答案。 选择圆形(1.12,1)取1.10。 选择圆形(1.15,1)取1.20。

但我需要如下结果。

Ex: 12.34  = 12.30
Ex: 12.35 = 12.35
Ex: 12.36 = 12.40
Ex: 12.95 = 12.95
Ex: 12.96 =13.00

请帮助我

Maideen

2 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,并且你希望在小数点后的两个点中舍入到0/5,我会做类似的事情:

out = round(in * 20.0) * 0.05

基本上做的是将数字in乘以100以对整数而不是浮点数进行操作。然后除以5以四舍五入到0或5的位置(100/5 = 20)。在四舍五入之后,将0.05乘以结果以恢复旧范围。

您可以将round更改为floorceil,如果这是您所追求的。

答案 1 :(得分:0)

我认为这会做你想要的(在SQL Server上。)我想不出一个更直接的方式。

round(x, 1, 1) +
    0.05 * case round(x * 100, 0, 1) % 10
        when 6 then 2 when 7 then 2 when 8 then 2 when 9 then 2
        when 5 then 1
        else 0
    end

我想了一下,你可能更喜欢这个:

    case round(x * 100, 0, 1) % 10
        when 5 then round(x, 1, 1) + 0.05 -- truncate and add back the 0.05
        else round(x, 1)                  -- round normally
    end