11,928,078 members (42,957 online)

Email

Password

Sign in using

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?

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

Jaykay832148

Use the Modulus operator: "x % 10" will return 0 if x == 10.

Comments

Thank you for the suggestion. Could you please show me where I need to set this in the code?

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...

Possibly change it to:

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

return result % 10;

Just a thought...

Works perfect! Thank you so much.

Welcome!

5, Your Patience,

--SA

--SA

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

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

CodeProject,
503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada
+1 416-849-8900 x 100