我希望能夠將數字舍入爲n中的有效數字。所以:舍入爲SQL中的重要數字
123.456 rounded to 2sf would give 120
0.0rounded to 2sf would give 0.0012
我知道ROUND()函數,其四捨五入小數點後n位而不是有效數字。
我希望能夠將數字舍入爲n中的有效數字。所以:舍入爲SQL中的重要數字
123.456 rounded to 2sf would give 120
0.0rounded to 2sf would give 0.0012
我知道ROUND()函數,其四捨五入小數點後n位而不是有效數字。
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
我想我已經管理了它。
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
改編了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(NUM, -ve NUM)四捨五入到小數點
左側對於剛剛一次性的,ROUND(123.456,-1),ROUND(0.00123,4) 返回請求的答案((120,0.0012)
這樣做效果很好,比我想出的要簡單得多:-) – Paul 2009-12-17 11:09:24
儘管必須確保@數字不是0. – Paul 2009-12-17 11:18:07
確實;相應更新。 – Brann 2009-12-17 11:22:03