Show zero on the left using the Tostring method

Asked

Viewed 1,555 times

7

I have roughly the following code implemented in c#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Teste
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(0134.ToString());
        }
    }
}

But it does not display the int 0134 whole:

inserir a descrição da imagem aqui

The 0 to the left is not showing.

  • 1

    Already tried "0134". Tostring()?

  • Works but wanted to convert int

2 answers

8


0134.ToString("D4");

So somehow it must pass how many elements exist in the integer, if for example its integer is 00134, the first element would not appear, it would be necessary to change D4 to D5

  • 1

    Thank you worked.

  • 1

    You can see a full list of parameters here

8

Abbreviated form (Default)

Format: .ToString("D[n]") or .ToString("d[n]")

The n is optional and means the size of the string, and if the number does not reach the set size a string is completed with 0 to the left.

Ex:

  123.ToString("D");  //-> Saída: "123"
  123.ToString("D1"); //-> Saída: "123"
  123.ToString("D2"); //-> Saída: "123"
  123.ToString("D3"); //-> Saída: "123"
  123.ToString("D4"); //-> Saída: "0123"
  123.ToString("D5"); //-> Saída: "00123"

Source | MSDN


Explicit form (Custom form)

There is also the explicit form, which is more flexible and you can do the same thing than the abbreviated form.

Ex:

123.ToString("00000"); //-> Saída: "00123"
123.ToString("000");   //-> Saída: "123"
123.ToString("0-0-0"); //-> Saída: "1-2-3";
123.ToString("0-0");   //-> Saída: "12-0";

Source | MSDN

Browser other questions tagged

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