1
protected void Page_Load(object sender, EventArgs e)
{
    lab.Text = FormatTelephoneNumber("0034523");
}

public static string FormatTelephoneNumber(string value)
{
   value = new System.Text.RegularExpressions.Regex(@"\D").Replace(value, string.Empty);
   return Convert.ToInt64(value).ToString(" #- ###-###");

}

Gives Output:

34-523

But I need output:

0-034-523

0034523 would Become 0-034-523 and 00345 would become 0-034-5 (no extra valeue or 0- 000-345)

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Aravindh
  • 25
  • 9
  • use [PadLeft(7, '0')](http://msdn.microsoft.com/en-us/library/system.string.padleft%28v=vs.110%29.aspx) to add `0` characters to your string before formatting – Mivaweb Dec 19 '14 at 11:02
  • 2
    Would you want inputs of "034523", "34523", "0034523" to give different results? If so, you should definitely *not* be converting them to integers. – Jon Skeet Dec 19 '14 at 11:04
  • return Convert.ToInt64(value).ToString(" #- ###-###"); this line use 0 value not converted. so how to value return. please give example. – Aravindh Dec 19 '14 at 11:18

3 Answers3

4

According to MSDN, you could use 0 instead of #

value.ToString("0- 000-000")
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
HoXa
  • 153
  • 9
  • 2
    Maybe add some code so that the person does not need to go elsewhere. – Anthony Horne Dec 19 '14 at 11:03
  • 0034523 would Become 0-034-523 and 00345 would become 0-034-5 (no extra valeue or 0- 000-345) Please Help me any one – Aravindh Dec 19 '14 at 11:07
  • return Convert.ToInt64(value).ToString(" #- ###-###"); this line use 0 value not converted. so how to value return. please give example – Aravindh Dec 19 '14 at 11:19
4

You should not convert it to int. Perform the regex on the string itself. Converting to int will ignore the leading 0's.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Krishnandu Sarkar
  • 494
  • 1
  • 6
  • 21
3

Use 0- 000-000 as format instead.

To get the additional requirement for the format, use two formats:

int val = Convert.ToInt32(value);

if (val < 1000)
{
    return val.ToString("0-000-0");
}
else
{
    return val.ToString("0-000-000");
}

The 0 is used to indicate padding.

According to MSDN:

Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325