Problem with PadLeft [duplicate]

2

I have a problem using the PadLeft method. I need to put some zeros in front of a string, but I can not. For example:

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

Theoretically, the string "newValue" should be set to "000002001795", right? But this is not working ...

    
asked by anonymous 24.02.2017 / 13:40

3 answers

7
  

Theoretically, the string "newValue" should be set to "000002001795", right?

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

As 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
    
24.02.2017 / 14:05
3

The method PadLeft , adds characters to the left until it completes its string to complete the number of characters entered, if the string already has at least that amount of characters nothing it will happen.

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

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

The value of newValue would be 0002001795 , as it would append 30 to the left until it completes 10 characters.

    
24.02.2017 / 14:05
2

The first argument is the maximum amount (totalWidth) that the string must have. You said that the maximum size is 5, 2001795 is longer than 5 characters, so you did not have to complete it.

Correct form:

 string newValue = value.PadLeft(12,'0');

link

    
24.02.2017 / 14:05