Keylee
Keylee

Reputation: 783

Line up Characters

I have a combobox made up of two numbers; inches and millimetres. At the moment it is looking hideous. I am wondering if some of the gurus here have anyway of lining the character '|' or at least make it nicer?

enter image description here

A bit of background info, the number inches and millimetres are separate strings which I append together like so:

Size(in) + " (In) | " + Size(mm) + " (mm)"

Upvotes: 0

Views: 161

Answers (2)

Kjartan
Kjartan

Reputation: 19111

Use String.PadRight(i); and String.PadLeft(i); where i is a nr. of spaces to "fill":

Example:

// Just to simplify a little, create vars:
var inches = Size(in) + " (In) ";
var mm = " + Size(mm) + " (mm)";

var formatted = inches.PadRight(15) + "|" + mm.PadLeft(15); 

Example of output using 15 for the padding value (obviously, you can adjust this as needed):

43 inches      |         123 cm
445554 inches  |       12345 cm

Upvotes: 1

Sayse
Sayse

Reputation: 43300

Possibly the cleanest way would be to format every number to have 3 decimal places for at least inches. This still won't be perfect however since the letter font width won't be perfect, to fix that you'd need to use a monospaced font.

To format to 3dp you can use the following

String.Format("{0:f3}", Size(in)) + " (In) | " + Size(mm) + " (mm)"

Since you have some values that are 2 digits before the decimal you can always use PadLeft to align these, but again this doesn't always work well without a monospaced font..

String.Format("{0:f3}", Size(in)).PadLeft(5, ' ') // or (5, '0')

Upvotes: 2

Related Questions