Eddie
Eddie

Reputation: 205

How to add spaces to a string to make string have 6 characters

I need to make a string to have a fixed 6 character. My original string length is smaller than 6, so I need to add space to and the end of my string. Here's my code

par = Math.Round(par / 1000, 0);
parFormat = par.ToString() + new string(' ', 6 - par.ToString().Length);

I got "count cannot be negative" error message.

Upvotes: 4

Views: 3138

Answers (2)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

You can use PadRight() function to add the specified character to the right of the string for the remianing length.

parFormat = par.ToString().PadRight(6,' ');

Note: by default PadRight() adds space so you can use PadRight with single parameter as below:

parFormat = par.ToString().PadRight(6);

Upvotes: 2

BradleyDotNET
BradleyDotNET

Reputation: 61349

The correct way to do this is using String.PadRight:

parFormat = par.ToString().PadRight(6);

In your method, you could have a int much greater than 6 digits long. This would return a negative length when performing your own pad function. You could also use:

par = Math.Round(par / 1000, 0);

parFormat = par.ToString() + new string(' ', Math.Max(0, 6 - par.ToString().Length));

To make sure you don't go negative. Using PadRight will be much easier though!

MSDN for PadRight: MSDN

Upvotes: 8

Related Questions