Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 948
Eddie Avatar asked Sep 18 '25 00:09

Eddie


1 Answers

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

like image 101
BradleyDotNET Avatar answered Sep 20 '25 15:09

BradleyDotNET