Luhn algorithm or Mod10 check

After searching the internet for a whole 10 minutes I found loads of examples of code that will check to see if somthing passes a 'mod10' check but none that will actualy create the check digit in the first place.

So after a bit of research, here it is. A very simple way to generate a mod10 check digit and append it to the end of a number...

<cfscript>
function createMod10(number)
{
   // this is an implementation of the Luhn algorithm or Luhn formula,    // also known as the "modulus 10" or "mod 10" algorithm,    // it calculates the check digit for a number and appends it to the end of the orignal string
   // this function generates the check digit and appends it to the orignal string
var nDigits = Len(arguments.number);
var sum = 0;
   var i=0;
var digit = "";
var checkdigit = 0;
for (i=0; i LT nDigits; i=i+1)
{
digit = Mid(arguments.number, nDigits-i, 1);
      if(NOT (i MOD 2))
      {
         digit = digit+digit;
         // check to see if we should add          if(len(digit) gt 1)
         {
            digit = left(digit,1) + right(digit,1);
         }
      }
      checkdigit = checkdigit + digit;
}
// divid by 10 checkdigit = checkdigit mod 10;
if(checkDigit neq 0) checkDigit = 10 - checkDigit;
return arguments.number & checkdigit;
}

</cfscript>

UPDATE: there was a slight mistake in the first version - this is better

Comments
James's Gravatar Or if you're using ColdFusion 7, you can use the isValid("creditcard",cardNumber) function which does the same checking :)
# Posted By James | 9/29/06 6:42 PM
Lucas Sherwood's Gravatar yep, that does check it - this function actualy makes a valid number including check digit
# Posted By Lucas Sherwood | 9/30/06 9:27 PM
warhammer gold's Gravatar Luhn algorithm or Mod10 check
# Posted By warhammer gold | 10/9/08 7:14 PM