Skip to content

Instantly share code, notes, and snippets.

@mizuneko
Last active November 18, 2018 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizuneko/026456bae937e6591a4ac0f13297fec1 to your computer and use it in GitHub Desktop.
Save mizuneko/026456bae937e6591a4ac0f13297fec1 to your computer and use it in GitHub Desktop.
[13桁のJANチェックデジット]
/// <summary>
/// JANコードの13桁タイプのチェックデジットを算出
/// </summary>
/// <param name="code">JANコード</param>
/// <returns></returns>
private int calcJAN13CheckDigit(string code)
{
if (!Regex.IsMatch(code, @"^[0-9]{12,13}$"))
{
throw new Exception("対象のJANコードが数字12桁または数字13桁になっていません。");
}
var val = code.Substring(0, 12);
// 1. 偶数桁の合計
int sumEven = val.Where((c, index) =>
index % 2 == 1).Select(c =>
int.Parse(c.ToString())).Sum();
// 2. 奇数桁の合計
int sumOdd = val.Where((c, index) =>
index % 2 == 0).Select(c =>
int.Parse(c.ToString())).Sum();
// 3. 偶数桁の合計 × 3 + 奇数桁の合計
int calc = sumEven * 3 + sumOdd;
// 4. 3で算出した値の1の位を取得
int subVal = calc % 10;
// 5. 10から4で取得した値を引いた結果の1の位がチェックデジット
return (10 - subVal) % 10;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment