我希望能够在 SQL 中将一个数字四舍五入为 n 个有效数字。所以:
123.456 rounded to 2sf would give 120
0.00123 rounded to 2sf would give 0.0012
我知道 ROUND() 函数,它舍入到 n 位小数而不是有效数字。
我希望能够在 SQL 中将一个数字四舍五入为 n 个有效数字。所以:
123.456 rounded to 2sf would give 120
0.00123 rounded 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
为那些看起来像我的人改编了 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)
我想我已经成功了。
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
您可以在四舍五入之前除以 100,然后乘以 100...