Search code examples
.netvb.netformatbytedigits

I would like to Convert a Byte to 3 digits in VB.net


For example:

If the Byte value is 5, I would like it to be displayed as 005.

If the Byte value is 10, I would like it to be displayed as 010.

Basically, I always want 3 digits. 119 would remain 119.

I'm aware of .padleft, but do not want to use an if statement. I tried Format("D3") with no luck.

Any suggestions would be appreciated.


Solution

  • If you are using String.Format, you need to specify the index for the parameter, not just D3, so it would be something like this:

    Dim r As Byte = 10
    Console.WriteLine(String.Format("{0:D3}", r))
    

    Alternatively, you could just use D3 into the ToString of r:

    Dim r As Byte = 10
    Console.WriteLine(r.ToString("D3"))