How to convert Enum to int by filling with zero on the left?

Asked

Viewed 108 times

1

Ladies and gentlemen, I have a question here of converting a enum in a string, but I need the conversion to be filled with zero to keep 2 digits.

Example

public enum System
{
    Unknown = 0,
    Mirror = 3,
    Order = 17
}

the Enum Mirror the out put would be "03".

tried with this example below worked

        int value;
        value = 3;
        Console.WriteLine(value.ToString("D2"));
        // Displays 03

But with Enum it doesn’t work.

Console.WriteLine(SourceSystem.Mirror.ToString("D2"));

The Following error appears:

System.FormatException 
Message=Format String can be only "G", "g", "X", "x", "F", "f", "D" or "d".....

Follows the enum:

    public enum SourceSystem
  {
    Unknown = 0,
    Mirror = 3,
    MirrorTrident = 17
  }

1 answer

1


First you need to take the amount with a cast for example, and then turn into string, the pattern of ToString() of enum is to give the description of his name.

using static System.Console;

public class Program {
    public static void Main() {
        WriteLine(((int)SourceSystem.Mirror).ToString("D2"));
    }
}

public enum SourceSystem {
    Unknown = 0,
    Mirror = 3,
    MirrorTrident = 17
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.