12,406,986 members (60,629 online)
Rate this:
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?

```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 21-Feb-11 0:27am

Rate this:

## Solution 1

Use the Modulus operator: "x % 10" will return 0 if x == 10.
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!
SAKryukov 21-Feb-11 21:50pm

--SA
Rate this:

## Solution 2

try this,

```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;
}
```

Top Experts
Last 24hrsThis month
 OriginalGriff 265 Karthik Bangalore 235 Richard MacCutchan 220 Afzaal Ahmad Zeeshan 75 Ruselo Riva Asentista 40
 OriginalGriff 8,027 Karthik Bangalore 3,541 ppolymorphe 3,420 Richard MacCutchan 2,652 F-ES Sitecore 2,300