Wednesday, March 05, 2008

GS1 Check Digit Calculator

I wrote a check digit calculator, maybe somebody will need it.
public static class CheckDigitCalculator {

public static int CalculateCheckDigit(string input) {
int sum = CalculateSum(input);
int checkDigit = CalculateCheckDigit(sum);
return checkDigit;
}

private static int CalculateSum(string input) {
int factor = 3;
int sum = 0;
for (int i = input.Length; i > 0; i--) {
sum += Convert.ToInt32(input[i - 1].ToString())
* factor;
factor = 4 - factor;
}
return sum;
}

private static int CalculateCheckDigit(int sum) {
if (sum % 10 == 0) {
return 0;
} else {
int nearestEqualOrHigherMultipleOfTen =
(sum / 10) * 10 + 10;
return nearestEqualOrHigherMultipleOfTen - sum;
}
}

}
Note: The perfect one should check for the input string only contains numeric values.

No comments: