Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# padLeft, not adding pad

Tags:

c#

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;
  }
like image 925
Jeff Longo Avatar asked Dec 31 '25 15:12

Jeff Longo


2 Answers

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");
}
like image 56
BlueMonkMN Avatar answered Jan 05 '26 03:01

BlueMonkMN


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.

like image 26
Matt LaCrosse Avatar answered Jan 05 '26 05:01

Matt LaCrosse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!