Thursday, December 16, 2010

Dual Mod 10 Check Digit

Check Digit Calculation - Note: The Last number of a CC Number is its check digit
  1. Start from the last digit and move to the first digit.
  2. Every other number is doubled.
  3. If it is a two-digit number, add the digits together.
  4. Keep a running sum.
  5. At the end, get the rightmost digit of the sum.
  6. Subtract that number by 10
  7. The rightmost digit of that number is the check digit
Example Calculation:
Number:  00123456789
Digit: 9 * 2 = 18 = (1 + 8) = 9
Sum: 9
Digit: 8 * 1 = 8 = (0 + 8) = 8
Sum: 17
Digit: 7 * 2 = 14 = (1 + 4) = 5
Sum: 22
Digit: 6 * 1 = 6 = (0 + 6) = 6
Sum: 28
Digit: 5 * 2 = 10 = (1 + 0) = 1
Sum: 29
Digit: 4 * 1 = 4 = (0 + 4) = 4
Sum: 33
Digit: 3 * 2 = 6 = (0 + 6) = 6
Sum: 39
Digit: 2 * 1 = 2 = (0 + 2) = 2
Sum: 41
Digit: 1 * 2 = 2 = (0 + 2) = 2
Sum: 43
Digit: 0 * 1 = 0 = (0 + 0) = 0
Sum: 43
Digit: 0 * 2 = 0 = (0 + 0) = 0
Sum: 43
Digit: * 1 = 0 = (0 + 0) = 0
Sum: 43
Rightmost Digit of Sum: 3
Check Digit: 10 - (3) = 7
Javascript Code to Calculate Check Digit:
function dualMod10(str,checkDigit){
                str=str+''; //Convert to string
                var weight=2; /* weight to apply to digit being checked */
                var sum=0; /* sum of weights */
                var digit; /* digit being checked */
                /* compute the sum */
                for (var cnt = str.length; cnt>0; cnt--){
                                digit = weight * (str.charAt(cnt-1));
                                /* add tens digit to ones digit to the sum */
                                sum = sum + Math.floor(digit / 10) + (digit % 10);
                                weight=weight==2?1:2;
                }
                /* subtract ones digit of the sum from 10 return ones digit of result */
var mod = (10-sum%10)%10;
                return (mod==(checkDigit*1) );
}
PHP Code to Calculate Check Digit:
function dualMod10($str,$checkDigit){
                $weight=2; /* weight to apply to digit being checked */
                $sum=0; /* sum of weights */
                /* compute the $sum */
                for ($cnt = strlen($str); $cnt>0; $cnt--){
                                $digit = $weight * ($str{($cnt-1)});
                                /* add tens digit and ones digit to the sum */
                                $sum = $sum + floor($digit / 10) + ($digit % 10);
                                $weight=$weight==2?1:2;
                }
                /* subtract ones digit of the sum from 10 return ones digit of that result */
                $mod = (10-$sum%10)%10;
                return ($mod==($checkDigit) );
}

No comments: