Format integer value in "000" format

Asked

Viewed 328 times

4

In vb6 used the following line of code that allowed formatting the value "1" to "001"

Format$(Nivel, "000")

In C# I am using the following with similar nomenclature.

string.Format("000", 1);

However the return value is always "000"

3 answers

6

It’s possible that way too.

int a  =  3;
string valor = a.ToString("D3");
  • I didn’t understand the -1 !!!

  • "D3" also adds the 3 digits.

  • Correct, I also did not understand the problem, so of my question.

4


  • You can also use the direct format on interpolated string (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interpolated-strings), which is actually a shortcut to the String.Format(), thus: $"{i:000}"

3

The right way to do what you want is by using the PadLeft():

string valor = "1";
valor.PadLeft(3, '0');
  • would not be valor.PadLeft(3,'0'); ?

  • ops, that’s right :P I’ll correct the answer. Vlw, @Leandroangelo

Browser other questions tagged

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