Jeff Longo
Jeff Longo

Reputation: 191

C# padLeft, not adding pad

I am writing a method to format a phone number and also add padding to the beginning if there are less than 10 digits in the initial array. I am only failing use cases where less than 10 digits are input and my method is clearly not adding the padding. The most common mistake is using the wrong padcount parameter. I am sure I am missing something simple.

public static string CreatePhoneNumber(int[] numbers)
  {
    string numbas = string.Join("", numbers);

    string ammendNumbas = numbas;

    char pad = '0';

    if ( numbas.Length < 10) 
    {
        ammendNumbas = numbas.PadLeft(10, pad);
    }

    string formatString = "(###) ###-####";
    var returnValue = Convert.ToInt64(ammendNumbas)
                 .ToString(formatString.Substring(0,ammendNumbas.Length+4))
                 .Trim();
     return returnValue;
  }

Upvotes: 2

Views: 659

Answers (3)

Matt LaCrosse
Matt LaCrosse

Reputation: 809

What BlueMonk said is correct but you can do the padding with String.Format

  public static string CreatePhoneNumber(int[] numbers)
  {
      string phoneNumberStr = string.Join("", numbers);

      var phoneNumber = Convert.ToInt64(phoneNumberStr);

      return String.Format("{0:(###) ###-####}", phoneNumber);
  }

This is not tested but should work.

Upvotes: 3

BlueMonkMN
BlueMonkMN

Reputation: 25601

When you use Convert.ToInt64 you would be removing all padding because padding can only be applied to strings. You would need to not convert the value back to an integer after applying padding.

I think what you want is this:

public static string CreatePhoneNumber(int[] numbers)
{
   Int64 numbas = Convert.ToInt64(string.Join("", numbers));
   return numbas.ToString("(000) 000-0000");
}

Upvotes: 6

Lukas Boersma
Lukas Boersma

Reputation: 1082

When you call Convert.ToInt64, the information of leading zeroes is lost. You can use substrings of your padded string representation to extract the digit groups:

public static string CreatePhoneNumber(int[] numbers)
{
    var numberString = string.Join("", numbers);
    var paddedNumbers = numberString.PadLeft(10, '0');
    return $"({paddedNumbers.Substring(0, 3)}) {paddedNumbers.Substring(3, 3)}-{paddedNumbers.Substring(6)}";
}

Upvotes: 1

Related Questions