Problem with Padleft

Asked

Viewed 1,098 times

2

I have a problem using the Padleft method. I need to put some zeros in front of a string, but I’m not getting it. For example:

string value = "2001795";
string newValue = value.PadLeft(5, '0');

Theoretically, the string "newValue" should have the value "000002001795", right? But this is not working...

3 answers

7


Theoretically, the string "newValue" should have the value "000002001795", right?

No. The PadLeft serves to complete a string with any character, which is passed as the second parameter of the method, until it reaches the number of characters entered in the first parameter.

For example:

var value = "123";
var newValue = value.PadLeft(5, '0');

// Saída 00123

If you only need to put 5 zeros in front of the string, you only need to concatenate.

var value = "123";
var newValue = "00000" + value;

// Saída 00000123
  • Thank you very much! Now I understand, I thought the first parameter was the amount of characters that are entered. Now I understand, thank you very much!

3

The method PadLeft, adds characters to the left until you complete your string complete the number of characters reported, if the string already have at least this amount of characters nothing will happen.

In your case, it will add 0 to the left until your string complete 5 characters, as your variable has 7 characters, nothing will happen. If you replace for example with:

string value = "2001795";
string newValue = value.PadLeft(10, '0');

The value of newValue would be 0002001795, because he would add 3 0 left until he completed 10 characters.

  • Thank you very much! Now I understand, I thought the first parameter was the amount of characters that are entered. Now I understand, thank you very much!

2

  • Thank you very much! Now I understand, I thought the first parameter was the amount of characters that are entered. Now I understand, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.