I have a Project for my c# programming class; writing a program that can read an employee file and a sales slip file and process the two. I have completed the 2 arrays I needed and they fill in nicely. My problem is when I go to print out the results in console mode. My arrays are of type decimal. I need to have all the numbers right justified at a certain position and the only way I know how to do so is with the function .PadRight/.PadLeft , which only work for strings I see. Is there any other way to do this or should I just Convert.ToString each value?
-
3Do you have an example of some of your input and expected output? It may make it quite a bit easier to determine what would work best.Rion Williams– Rion Williams2016-04-28 16:10:00 +00:00Commented Apr 28, 2016 at 16:10
-
telling us vs showing us what you have in regards to where the issues are happening are 2 different things.. please show code where the unexpected is happeningMethodMan– MethodMan2016-04-28 16:11:02 +00:00Commented Apr 28, 2016 at 16:11
-
stackoverflow.com/questions/4579506/…pm100– pm1002016-04-28 16:14:51 +00:00Commented Apr 28, 2016 at 16:14
Add a comment
|
2 Answers
If you simply need to output your values padded using the Console, you can simply format them using Composite Formatting and it's {0,spaces-to-format} syntax :
// Example array of decimals
var input = new decimal[]{ 12.24m, 199.99m, 1.0m, 42.42m, 100321.123m };
// Format each value to 10 digits
foreach(decimal d in input)
{
// Format each value to 10 places (right-justfied)
// You could alternatively use d.ToString("{0,10")
Console.WriteLine("{0,10}",d);
}
You can see a working example of this here and demonstrated below :
Comments
You're pretty much looking at
decimal val = 10m;
//Or PadLeft
string formattedVal = val.ToString().PadRight(10, ' ');
1 Comment
Ashok Prabhu
this is what my code looks like for printing it to console.
