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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With