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

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

我知道回合()函数,该功能可圆形到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最受欢迎的答案。

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

/ *感觉太长了,无法发表评论 */

圆形(num,sf -1-地板(log10(abs(num))))

  • 进行工作的部分 - 正常使用该数字,但要舍入的长度是计算的
  • ABS确保积极
  • log10获得数字大于0的数字数量
  • 地板的整数最大小于最终的数字
  • 因此,总是圆形并给出一个整数
  • SF -1-地板(...)给出负数
  • 工作是因为小数点左侧的圆形(num,-ve num)回合

  • 仅一击,回合(123.456,-1)和圆(0.00123,4)返回请求的答案(((120,0.0012)

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

我想我已经管理了。

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top