Display zero on the left using the ToString method

7

I have more or less 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 int 0134 all:

O 0 on the left is not appearing.

    
asked by anonymous 31.03.2017 / 07:52

2 answers

8

0134.ToString("D4");

In this way somehow you must pass as many elements as there are in the integer, if for example your integer is 00134 , the first element would not appear, you would need to change D4 to D5

    
31.03.2017 / 08:07
8

Abbreviated Form (Default)

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

n is optional and means the size of string , and if the number does not reach the set size the string is completed with 0 on 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)

There is also the explicit form, which is more flexible and can do the same thing as 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

    
31.03.2017 / 13:42