Home Forums SQL Server 7,2000 T-SQL Banker''s rounding in T-SQL (like Math.Round in .NET) RE: Banker''''s rounding in T-SQL (like Math.Round in .NET)

  • Jeff - I think that may not work for the 3.445657545 example (which should go to 3.45).

    Here's an alternative (non-looping) solution:

    CREATE FUNCTION dbo.RoundBanker (@x money, @DecimalPlaces tinyint)

    RETURNS money AS

    BEGIN

    set @x = @x * power(10, @DecimalPlaces)

    return

      case when @x = floor(@x) then @x

      else

        case sign(ceiling(@x) - 2*@x + floor(@x))

        when 1 then floor(@x)

        when -1 then ceiling(@x)

        else 2*round(@x/2,0) end

      end / power(10, @DecimalPlaces)

    END

    select dbo.RoundBanker(3.454,2) --> 3.45

    select dbo.RoundBanker(3.455,2) --> 3.46

    select dbo.RoundBanker(3.445,2) --> 3.44

    select dbo.RoundBanker(3.456,2) --> 3.46

    select dbo.RoundBanker(3.445657545, 2) --> 3.45

    Ryan Randall

    Solutions are easy. Understanding the problem, now, that's the hard part.