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)

  • This SQL uses the banker's rounding algorithm:

    DECLARE@Decimalssmallint

    set@Decimals= 2

    select BRAmt

    ,BRExpectedAmt

    , CASE

    WHEN 5 = ( ROUND(BRAmt * POWER( 10, @Decimals + 1 ) ,0,1) - (ROUND(BRAmt * POWER( 10, @Decimals ) ,0,1) * 10) )

    AND 0 = cast( ( ROUND(BRAmt * POWER( 10, @Decimals ) ,0,1) - (ROUND(BRAmt * POWER( 10, @Decimals - 1 ) ,0,1) * 10) ) AS INTEGER ) % 2

    then ROUND(BRAmt,@Decimals, 1 )

    ELSE ROUND(BRAmt,@Decimals, 0 )

    END as BRBankersRoundedAmt

    FROM(select cast ( 3.454 as numeric(8,4) ) , cast(3.45 as numeric(6,2) ) union all

    select cast ( 3.455 as numeric(8,4) ) , cast(3.46 as numeric(6,2) )union all

    select cast ( 3.445 as numeric(8,4) ) , cast(3.44 as numeric(6,2) )union all

    select cast ( 3.456 as numeric(8,4) ) , cast(3.46 as numeric(6,2) )

    ) as BR (BRAmt, BRExpectedAmt)

    SQL = Scarcely Qualifies as a Language