Get check digit (Mod 11) implementation in c#

Fraga picture Fraga · Aug 10, 2011 · Viewed 11.3k times · Source

Can anyone give me the code in C#... for getting the Verification Digit with Mod11?

Thanks.

public class Mod11 
{
    public static string AddCheckDigit(string number); 
}

Example:

Mod11.AddCheckDigit("036532");

Result: 0365327

Answer

Fraga picture Fraga · Aug 10, 2011

The code is here:

public class Mod11
{
    public static string AddCheckDigit(string number)
    {
        int Sum = 0;
        for (int i = number.Length - 1, Multiplier = 2; i >= 0; i--)
        {
            Sum += (int)char.GetNumericValue(number[i]) * Multiplier;

            if (++Multiplier == 8) Multiplier = 2;
        }
        string Validator = (11 - (Sum % 11)).ToString();

        if (Validator == "11") Validator = "0";
        else if (Validator == "10") Validator = "X";

        return number + Validator;
    }
}

I hope it help some one.

PROBLEMS: If the remainder from the division is 0 or 1, then the subtraction will yield a two digit number of either 10 or 11. This won't work, so if the check digit is 10, then X is frequently used as the check digit and if the check digit is 11 then 0 is used as the check digit. If X is used, then the field for the check digit has to be defined as character (PIC X) or there will be a numeric problem.