Click here to Skip to main content
15,885,182 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hi all,

I've been trying to make a mod10 check digit calculator in C#. I've found a snippet that works, however, I cannot seem to find out how to tell the program to return 0 if the check digit is 10. It works for all other numbers except the ones that return 10. Can somebody please help me with where to insert this?

C#
public static int GetMod10Digit(string data)
        {
            int sum = 0;
            bool odd = true;
            for (int i = data.Length - 1; i >= 0; i--)
            {
                if (odd == true)
                {
                    int tSum = Convert.ToInt32(data[i].ToString()) * 2;
                    if (tSum >= 10)
                    {
                        string tData = tSum.ToString();
                        tSum = Convert.ToInt32(tData[0].ToString()) + Convert.ToInt32(tData[1].ToString());
                    }
                    sum += tSum;
                }
                else
                    sum += Convert.ToInt32(data[i].ToString());
                odd = !odd;
            }
            return (((sum / 10) + 1) * 10) - sum;
        }
Posted

Use the Modulus operator: "x % 10" will return 0 if x == 10.
 
Share this answer
 
Comments
Jaykay832 21-Feb-11 6:46am    
Thank you for the suggestion. Could you please show me where I need to set this in the code?
OriginalGriff 21-Feb-11 6:50am    
Since mod10 is supposed to always return a number if the range 0 to 9, I would recommend you think about the "return" statement?

Possibly change it to:

int result = (((sum / 10) + 1) * 10) - sum;
return result % 10;

Just a thought...
Jaykay832 21-Feb-11 6:53am    
Works perfect! Thank you so much.
OriginalGriff 21-Feb-11 6:55am    
Welcome!
Sergey Alexandrovich Kryukov 21-Feb-11 21:50pm    
5, Your Patience,
--SA
try this,

C#
public static int GetMod10Digit(string data)
{

 int sumOfDigits = data.Where((e) => e >= '0' && e <= '9')
 .Reverse()
 .Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2))
 .Sum((e) => e / 10 + e % 10);
 //// If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid.
 return sumOfDigits % 10;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900