-3

I have phone numbers like this :

452341

12

45789632

Is there a way i can format them like this way :

00452341

00000012

45789632

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
Mehdi Souregi
  • 3,153
  • 5
  • 36
  • 53
  • 1
    Of course there is. Have you tried anything at all? – Equalsk Jan 30 '17 at 11:04
  • 2
    How do you declare the variable that stores the phonenumber? Is it an integer or a string? The answer is different – Steve Jan 30 '17 at 11:05
  • the variable is an integer – Mehdi Souregi Jan 30 '17 at 11:07
  • If you're storing phone numbers as integers, *that* should be the problem you fix. They're not really numbers. You don't perform mathematics with them. In reality, they're strings. That just happen to be composed of digits. – Damien_The_Unbeliever Jan 30 '17 at 11:08
  • If number is integer then you should have selected Ikram's answer. Ashkan's solution needs a conversion to string before padding. Later gives you intended result during conversion. – Vijay Jan 30 '17 at 11:33
  • Integer class has the tostring method since it inherits from the Object class, – Mehdi Souregi Jan 30 '17 at 11:52
  • but what i dont understand is how some people react with such questions with downvotes and some negatives comments, my question was clear, ive tried to look up if there is a similar questions in this site but in vain, the only possible duplicate is a little different because it does not contains the word "phonenumber" but it leads to the same answer. Besides you cannot delete your own question it says : "Sorry, this question has answers and cannot be deleted; flag it for moderator attention instead.", all you can do, is watch yourself being humiliated :) – Mehdi Souregi Jan 30 '17 at 11:52

3 Answers3

7

You cam use Padding:

Number.PadLeft(length, '0');

For example:

string num = "1234";
num.PadLeft(10, '0');

The result will be 0000001234

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
4
ToString("D8")

Here - MSDN - Decimal ("D") Format Specifier

NOTE:

PadLeft(length, '0'); does not work for negative numbers

Ex: (-1).Padleft(5, '0') --> 000-1

kgzdev
  • 2,770
  • 2
  • 18
  • 35
3

Use format with leading zeroes (Example for 8 symbols in number):

452341.ToString("D8");

if you have already strign use solution of Ashkan:

"452341".PadLeft(8, '0');
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49