views:

343

answers:

3

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

I am aware of the ROUND() function, which rounds to n decimal places rather than significant figures.

A: 

You could divide by 100 before rounding and then multiplying by 100...

grenade
That wouldn't work on the second example
Paul
Dividing, flooring and multiplying is a way of truncating to decimal places, rather than rounding to significant figures.
Paul
+2  A: 

select round(@number,@sf-1- floor(log10(abs(@number)))) should do the trick !

Successfully tested on your two examples.

Edit : Calling this function on @number=0 won't work. You should add a test for this before using this code.

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
That works well, and is much simpler than what I came up with :-)
Paul
Although must ensure @number isn't 0.
Paul
indeed ; updated accordingly.
Brann
A: 

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
Paul