Search code examples
c#string-formatting

How to deal with leading zeros when formatting an int value


have a bit of a blank. If I want to apply the following format (## ### ###) to an int value I would do this.

string myFormat = "## ### ###";
int myPin = 18146145;
Console.WriteLine(myPin.ToString(myFormat)); //18 146 145

Issue however is with the values of say "02112321" to be formatted as "02 112 321" applying this exact formatting "## ### ###". the 0 in this case would fall away.


Solution

  • You can use the 0 as format specifier. From the documentation :

    Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

    You can do like :

    02112321.ToString("00 000 000", CultureInfo.InvariantCulture)
    

    Edit: As indicate by @olivier-jacot-descombes, I miss a point. The OP want format a integer from a string to a string. Example "02112321" to "02 112 321".

    It's possible with a intermediate conversion, string to int to string. With the example, this done "02112321" to 02112321 to "02 112 321" :

    var original = "02112321";
    var toInt = int.Parse(original, CultureInfo.InvariantCulture);
    var formated = toInt.ToString("00 000 000", CultureInfo.InvariantCulture)