RetroCoder
RetroCoder

Reputation: 2685

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

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.

Upvotes: 8

Views: 12053

Answers (1)

Anthony Pegram
Anthony Pegram

Reputation: 126854

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);

Upvotes: 19

Related Questions