Skip to content

Adds support for cnpj alphanumeric values #634

@charllysonsouza

Description

@charllysonsouza

Description

Recently, the official Brazilian government decreed a new rule requiring that the CNPJ include not only digits, but also capital letters. This rule will come into effect in July 2026. At this time, most of systems are adapting. It would be interesting if we could generate a cnpj in this new format. I've tried to open a pull request with this feature, but without succeeded.

LINQPad Code Example

public static class ExtensionsForBrazil
{
   private static readonly int[] CnpjFirstDigitWeights = [5,4,3,2,9,8,7,6,5,4,3,2];
   private static readonly int[] CnpjSecondDigitWeights = [6,5,4,3,2,9,8,7,6,5,4,3,2];
   private const string AlphaNumericChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   private const string NumericChars = "0123456789";

   /// <summary>
   /// Cadastro Nacional da Pessoa Jurídica
   /// </summary>
   /// <param name="includeFormatSymbols">Includes formatting symbols.</param>
   public static string Cnpj(this Company c, bool includeFormatSymbols = true, bool includeOnlyDigits = false, bool includeOnlyAlphaNumerics = false)
   {
      string chars;

      if (includeOnlyDigits)
         chars = NumericChars;
      else if (includeOnlyAlphaNumerics)
         chars = AlphaNumericChars;
      else
         chars = c.Random.Bool() ? NumericChars : AlphaNumericChars;

      var cnpj = "";
      for (var i = 0; i < 8; i++)
         cnpj += chars[c.Random.Int(0, chars.Length - 1)];

      cnpj += "0001";

      var firstDigit = CalculateDigit(cnpj, CnpjFirstDigitWeights);
      cnpj += firstDigit;

      var secondDigit = CalculateDigit(cnpj, CnpjSecondDigitWeights);
      cnpj += secondDigit;

      if ( includeFormatSymbols )
         cnpj = $"{cnpj[0]}{cnpj[1]}.{cnpj[2]}{cnpj[3]}{cnpj[4]}.{cnpj[5]}{cnpj[6]}{cnpj[7]}/{cnpj[8]}{cnpj[9]}{cnpj[10]}{cnpj[11]}-{cnpj[12]}{cnpj[13]}";

      return cnpj;
   }

   private static int CalculateDigit(string cnpj, int[] weights)
   {
      var sum = cnpj.Select((value, i) => (value - '0') * weights[i]).Sum();
      var remainder = sum % 11;
      return remainder < 2 ? 0 : 11 - remainder;
   }
}

What alternatives have you considered?

n/a

Could you help with a pull-request?

Yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions