Round to n Significant Figures in SQL

前端 未结 4 1553
-上瘾入骨i
-上瘾入骨i 2021-02-18 14:38

I would like to be able to round a number to n significant figures in SQL. So:

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


        
4条回答
  •  忘掉有多难
    2021-02-18 14:45

    I think I've managed it.

    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
    

提交回复
热议问题