TSQL向上舍入十进制数

时间:2012-12-27 18:09:41

标签: sql-server tsql rounding

我有这个号码0.581183781439,我需要绕数字0.582

我正在尝试

SELECT ROUND (0.581183781439, 3)
-------------------------------
0.581000000000

这对ROUND函数有用吗?

4 个答案:

答案 0 :(得分:11)

DECLARE @Test TABLE (Col NUMERIC(38,12));

INSERT  @Test (Col)
SELECT 0.581183781439 
UNION ALL
SELECT 0.5815
UNION ALL
SELECT 0.581883781439
UNION ALL
SELECT -0.581883781439;

SELECT Col AS [Col],
    ROUND(Col, 3) AS StandardRounding_3decimals,
    ROUND(Col, 3, 1) AS Truncation_3decimals,
    FLOOR(Col*1000)/1000 AS RoundDown_3decimals,
    CEILING(Col*1000)/1000  AS RoundUp_3decimals 
FROM @Test;

结果:

Col             StandardRounding_3decimals Truncation_3decimals RoundDown_3decimals RoundUp_3decimals
--------------- -------------------------- -------------------- ------------------- -----------------
0.581183781439  0.581000000000             0.581000000000       0.581000            0.582000
0.581500000000  0.582000000000             0.581000000000       0.581000            0.582000
0.581883781439  0.582000000000             0.581000000000       0.581000            0.582000
-0.581883781439 -0.582000000000            -0.581000000000      -0.582000           -0.581000

答案 1 :(得分:6)

也许你需要这个?

SELECT ROUND(0.581183781439, 3,1) + .001

但正确的舍入为0.581

答案 2 :(得分:3)

我们可以编写一个T-SQL函数来舍入任意数量的小数位。

CREATE FUNCTION RoundUp (@value float, @places int) RETURNS float
AS
BEGIN
    RETURN SELECT CEILING(@value * POWER(10, @places)) / POWER(10, @places)
END
GO

SELECT Result = dbo.RoundUp(0.581183781439, 3)
  

结果

     

0.582

答案 3 :(得分:0)

加上一半的值并使用正常的回合将得到正确的结果。

SELECT ROUND (0.581183781439 + .0005, 3)

奖金:改为减去一半值,它将四舍五入。

EDIT :实际上,当值在小数点后三位为零时,它具有与上述答案相同的缺点。