In C #, how to use String.Format for a number and pad left by zeros, so its always 6 characters

I want to use C # format for this:

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

I tried to use String.Format, but to no avail.

+7
source share
1 answer

Formatting will not result in an error if there are too many digits. You can get a 6-digit string with left padding only with

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

If you need 7-digit strings that will be invalid, you just need to code it.

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

To use string.Format you must write

 string output = string.Format("{0:000000}", number); 
+18
source

All Articles