• Nice function.

    Tip 1: Instead of the CASE to get rid of negative values, use ABS.

    Tip 2: Add a CASE to work around the domain error you'd get from LOG10(0).

    Tip 3: Stop being lazy and use decimal instead of float. Because float can't represent many values exactly, you run the risk of errors. For instance:

    SELECT dbo.fix(1.15)   -- Returns 1.1 instead of 1.2

    alter

    function dbo.fix(@num numeric(36,18), @digits int) returns numeric(36,18) as

    begin

    declare @res float

    select @res = case when @num = 0 then 0

    else round(@num,@digits-1-floor(log10(abs(@num)))) end

    return (@res)

    end


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/