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;
}
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");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With