Taiwan CompanyID CheckCode

前言

要不是业主通知我,我还真不知道公司统一编号格式检查逻辑在今年3月前得做修正…(汗

实作

说明都在注解里

   /// <summary>
   /// 公司统一编号格式检查(2023年3月版)
   /// 政府公告附件下载:https://www.fia.gov.tw/singlehtml/3?cntId=c4d9cff38c8642ef8872774ee9987283
   /// 范例说明:https://www.chi.com.tw/blog/invoicelcud
   /// </summary>
   /// <param name="CompanyId"></param>
   /// <returns></returns>
   public static bool CheckCompanyId(string CompanyId)
   {
       //空值或非8码或非纯数字
       if (string.IsNullOrEmpty(CompanyId) || CompanyId.Trim().Length != 8 || int.TryParse(CompanyId, out int CompanyNo) == false)
       {
           return false;
       }

       bool is统编第7位数字为7 = (CompanyId.Substring(6, 1)=="7");

       int[] logics = new int[] { 1, 2, 1, 2, 1, 2, 4, 1 };//逻辑乘数

       int Z = 0;//垂直乘积之和 全部加总
       int Z1 = 0;
       int Z2 = 0;

       //逻辑乘数的数量与统编长度8码一致
       for (int i = 0; i < logics.Length; i++)
       {
           int num = Convert.ToInt32(CompanyId.Substring(i, 1));//统编单一数字拆解
           int j = num * logics[i];//乘积直写并上下相加
           int 乘积之和 = ((j / 10) + (j % 10));//垂直乘积之和(上下数字相加)
           
           if (is统编第7位数字为7 && i==6)//统编第7位数字是"7" && 走访到统编第7位数字时
           {
               //"乘积之和"为"10",但政府文件要我们取"0或1"两种情况(不是10)来相加。
               Z1 += 0;
               Z2 += 1;
              //Z 不理它
           }
           else
           {
               Z += 乘积之和;
               Z1 += 乘积之和;
               Z2 += 乘积之和;
           }
       }//end for
       //int old_checkNum = 10;//2023年以前的旧版
       int checkNum = 5;
       
       if (is统编第7位数字为7)
       {
           if ((Z1 % checkNum) == 0 || (Z2 % checkNum)==0)
           {
               return true;
           }
       }else if (Z % checkNum == 0)
       {
           return true;
       }
        
       return false;
   }