i have a luhn algorithm, i am trying to follow the steps on Wikipedia for the algorithm, and it works for the examples they give. and i thought it was correct. But it doesn't work on any of my personal cards. nor on any of the test values i have found around looking for a solution to this.
I have seen other solutions for this using lamba and inline linq. But i don't want to copy and paste anything. i would rather actually understand what i am coding.
49927398716 pass
49927398717 fail
1234567812345678 fail
1234567812345670 pass (mine fails this one)
my code is as follows.
private bool CalculateLuhnAlgorithm()
{
string newListOfNumbers = this._number; //this._number is a string
int sumOfAllValues = 0;
if (_cardType != CardType.Unavailable)
{
//odd numbers minus the check Digit.
for (int i = this._number.Length - 2; i > 0; i -= 2)
{
int number = (int)char.GetNumericValue(this._number[i]) * 2;
if (number >= 10)
{
string concatinatedNumber = number.ToString();
int firstNumber = (int)char.GetNumericValue(concatinatedNumber[0]);
int secondNumber = (int)char.GetNumericValue(concatinatedNumber[1]);
number = firstNumber + secondNumber;
}
newListOfNumbers = newListOfNumbers.Remove(i, 1);
newListOfNumbers = newListOfNumbers.Insert(i, number.ToString());
}
// add up the complete total
foreach (char c in newListOfNumbers)
{
sumOfAllValues += (int)char.GetNumericValue(c);
}
}
// get the luhn validity
return (sumOfAllValues %10) == 0;
}
newListOfNumbersis initialized as the string, then the odd number are doubled and replaced. Then the digits ofnewListOfNumbersare summed, which includes the last digit of the original string, the check digit. Also I totally agree that a check for the length of the string should be added.