Last active
November 18, 2018 07:55
-
-
Save mizuneko/026456bae937e6591a4ac0f13297fec1 to your computer and use it in GitHub Desktop.
[13桁のJANチェックデジット]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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