Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad a number with starting zero in .Net

I have a requirement to pad all single digits numbers with a starting zero. Can some one please suggest the best method? (ex 1 -> 01, 2 -> 02, etc)

like image 454
Alex Avatar asked Jan 28 '09 21:01

Alex


People also ask

How do you pad a number with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

How do you put a zero at the beginning of a string?

Use the padStart() method to add leading zeros to a string. The method allows us to pad the current string with zeros to a specified target length and returns the result.

What is the method to pad a numeric string on the left with zeros?

For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.

What is a zero padded number?

Zero padding is a technique typically employed to make the size of the input sequence equal to a power of two. In zero padding, you add zeros to the end of the input sequence so that the total number of samples is equal to the next higher power of two.


2 Answers

number.ToString().PadLeft(2, '0') 
like image 177
Rockcoder Avatar answered Oct 05 '22 23:10

Rockcoder


I'd call .ToString on the numbers, providing a format string which requires two digits, as below:

int number = 1; string paddedNumber = number.ToString("00"); 

If it's part of a larger string, you can use the format string within a placeholder:

string result = string.Format("{0:00} minutes remaining", number); 
like image 38
bdukes Avatar answered Oct 06 '22 01:10

bdukes