2009-12-17 56 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)