SQL Banker's Rounding Function

The Banker's Rounding, also known as the Gaussian Rounding or Rounding to Even, rounds a given number if its fraction is half to the nearest even number.

The bellow SQL function rounds any given decimal number to a number of given digits and returns the rounded decimal number. It reads the number from right to left depending on the number of digits required and then rounds it. If the fraction is not half, then common rounding takes place.

CREATE FUNCTION [dbo].[BankersRounding]
(
	@value DECIMAL(28, 10),
	@digits INT
)

RETURNS DECIMAL (28, 10)
AS
BEGIN

	DECLARE @roundedValue DECIMAL(28, 10)
	DECLARE @roundingType INT 
	
		IF (ABS(@value - ROUND(@value, @digits, 1)) * POWER(10, @digits + 1) = 5)
			BEGIN
			
				IF (ROUND(ABS(@value) * POWER(10, @digits), 0, 1) % 2 = 0)
					BEGIN
						SET @roundingType = 1 
					END
				ELSE
					BEGIN
						SET @roundingType = 0
					END
						
				SET @roundedValue = ROUND(@value, @digits, @roundingType)
			END
				
		ELSE
			BEGIN
				SET @roundedValue = ROUND(@value, @digits)
			END
						
	RETURN @roundedValue
END

In C# there's the Round method inside the Math class that can take an enumeration overload called MidpointRounding.ToEven that does the exact same thing.

Here's an example:

using System;

namespace BankersRoundingProject
{
    public class BankersRounding
    {
        public static decimal GetRoundedValue(decimal value, int digits)
        {
            return Math.Round(value, digits, MidpointRounding.ToEven);
        }
    }
}

No comments:

Post a Comment