How to add leading zeros to number in C#

3 Answers

0 votes
using System;

class Program
{
    static void Main() {
        int num = 7;

        Console.Write(num.ToString().PadLeft(3, '0'));
    }
}



/*
run:

007

*/

 



answered Jul 1, 2023 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        int num = 7;

        Console.Write(num.ToString("D3"));
    }
}



/*
run:

007

*/

 



answered Jul 1, 2023 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        int num = -4;

        Console.Write(num.ToString("D3"));
    }
}



/*
run:

-004

*/

 



answered Jul 1, 2023 by avibootz
...