Panda Pajama
Panda Pajama

Reputation: 1431

How do I pad a number in the absence of a minus sign with string.Format()?

I am overriding the ToString() method of a matrix class so I can copy the contents from the watch window into a text editor to perform further analysis.

The idea is that ToString() should return something like this:

[M11:-1.00 M12: 0.00 M13: 0.00 M14: 0.00]
[M21: 0.00 M22: 0.00 M23:-1.00 M24: 0.00]
[M31: 0.00 M32:-1.00 M33: 0.00 M34: 0.00]
[M41: 0.00 M42: 0.00 M43: 0.00 M44: 1.00]

Notice how positive numbers have an extra padding space to compensate for the space the minus sign consumes on negative numbers.

Currently, I am doing this:

    public override string ToString()
    {
        return string.Format("[M11:{0:0.00} M12:{1:0.00} M13:{2:0.00} M14:{3:0.00}]\n[M21:{4:0.00} M22:{5:0.00} M23:{6:0.00} M24:{7:0.00}]\n[M31:{8:0.00} M32:{9:0.00} M33:{10:0.00} M34:{11:0.00}]\n[M41:{12:0.00} M42:{13:0.00} M43:{14:0.00} M44:{15:0.00}]",
            M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44);
    }

This outputs the following:

[M11:-1.00 M12:0.00 M13:0.00 M14:0.00]
[M21:0.00 M22:0.00 M23:-1.00 M24:0.00]
[M31:0.00 M32:-1.00 M33:0.00 M34:0.00]
[M41:0.00 M42:0.00 M43:0.00 M44:1.00]

I would like to add padding spaces to positive numbers so they all line up nice, therefore making my debugging tasks easier.

Unfortunately, there seems to be no placeholder for the sign in string.Format().

I guess I could use .ToString() on each element, use Pad() and then assemble them all, but I still think there may be a way to achieve this without having to manually assemble the numbers and creating a lot of garbage in the meantime.

Is it possible to do this inside ToString()? or do I need to manually pad each number so the periods align nicely.

Upvotes: 4

Views: 1203

Answers (1)

to StackOverflow
to StackOverflow

Reputation: 124696

You can use a format similar to:

    [M11:{0: 0.00;-0.00} M12:{0: 0.00;-0.00}...

Look at the section headed The ";" Section Separator in the MSDN article you linked.

Upvotes: 5

Related Questions