Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c# how to use String.Format for a number and pad left with zeros so its always 6 chars

Tags:

c#

I want to use c# format to do this:

6 = "000006"
999999 = "999999"
100 = "000100"
-72 = error
1000000 = error

I was trying to use String.Format but without success.

like image 296
RetroCoder Avatar asked Oct 22 '11 01:10

RetroCoder


1 Answers

Formatting will not produce an error if there are too many digits. You can achieve a left-padded 6 digit string just with

string output = number.ToString("000000"); 

If you need 7 digit strings to be invalid, you'll just need to code that.

if (number >= 0 and number < 1000000)
{
     output = number.ToString("000000")
}
else 
{
     throw new ArgumentException("number");
}

To use string.Format, you would write

string output = string.Format("{0:000000}", number);
like image 69
Anthony Pegram Avatar answered Oct 23 '22 14:10

Anthony Pegram