2009-12-17 48 views
16

我希望能够将数字舍入为n中的有效数字。所以:舍入为SQL中的重要数字

123.456 rounded to 2sf would give 120 
0.0rounded to 2sf would give 0.0012 

我知道ROUND()函数,其四舍五入小数点后n位而不是有效数字。

回答

16

select round(@number,@sf-1- floor(log10(abs(@number))))应该做的伎俩!

已成功测试您的两个示例。

编辑:在@ number = 0上调用此函数将不起作用。在使用此代码之前,您应该为此添加一个测试。

create function sfround(@number float, @sf int) returns float as 
begin 
    declare @r float 
    select @r = case when @number = 0 then 0 else round(@number ,@sf -1-floor(log10(abs(@number)))) end 
    return (@r) 
end 
+0

这样做效果很好,比我想出的要简单得多:-) – Paul 2009-12-17 11:09:24

+0

尽管必须确保@数字不是0. – Paul 2009-12-17 11:18:07

+1

确实;相应更新。 – Brann 2009-12-17 11:22:03

0

您可以通过100四舍五入,然后乘以100除以之前...

+0

这不适用于第二个示例 – Paul 2009-12-17 11:00:00

+1

划分,地板和乘法是截断到小数位的一种方法,而不是四舍五入到有效数字。 – Paul 2009-12-17 11:18:45

0

我想我已经管理了它。

CREATE FUNCTION RoundSigFig(@Number float, @Figures int) 
RETURNS float 
AS 
BEGIN 

    DECLARE @Answer float; 

    SET @Answer = (
    SELECT 
     CASE WHEN intPower IS NULL THEN 0 
     ELSE FLOOR(fltNumber * POWER(CAST(10 AS float), intPower) + 0.5) 
       * POWER(CAST(10 AS float), -intPower) 
     END AS ans 
    FROM (
     SELECT 
      @Number AS fltNumber, 
      CASE WHEN @Number > 0 
       THEN -((CEILING(LOG10(@Number)) - @Figures)) 
      WHEN @Number < 0 
       THEN -((FLOOR(LOG10(@Number)) - @Figures)) 
      ELSE NULL END AS intPower  
     ) t 
    ); 

    RETURN @Answer; 
END 
0

改编了Brann给MySQL看到的最受欢迎的答案。

CREATE FUNCTION `sfround`(num FLOAT, sf INT) # creates the function 
RETURNS float # defines output type 
DETERMINISTIC# given input, will return same output 

BEGIN 

    DECLARE r FLOAT; # make a variable called r, defined as a float 

    IF(num IS NULL OR num = 0) THEN # ensure the number exists, and isn't 0 
     SET r = num; # if it is; leave alone 

    ELSE 
     SET r = ROUND(num, sf - 1 - FLOOR(LOG10(ABS(num)))); 
    /* see below*/ 
    END IF; 

    RETURN (r); 

END 

/*觉得太长时间放在注释*/

ROUND(NUM,SF - 1 - FLOOR(LOG10(ABS(NUM))))

  • 的一部分是否正常工作 - 对数字使用ROUND函数,但要计算的长度为
  • ABS确保为正
  • LOG10获取数字大于0的数字位数
  • FLOOR得到的最大整数大于该生成数
  • 所以始终下舍小并给出了一个整数
  • SF - 1 - FLOOR(...)给出了否定的数
  • 作品,因为ROUND(NUM, -ve NUM)四舍五入到小数点

  • 左侧对于刚刚一次性的,ROUND(123.456,-1),ROUND(0.00123,4) 返回请求的答案((120,0.0012)