Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string formatting and padding

Seems like this should be something straightforward, but I haven't been able to get it right. I've looked at http://idunno.org/archive/2004/14/01/122.aspx for reference.

Example: I would like to print a table of double values, with each double output having 3 decimal precision, and take up 10 spaces (left aligned). Conceptually, I tried something like this, but it only works with precision OR padding, not both:

foreach(line in lines)
{
    foreach (double val in line)
    {
         Console.Write("{0:0.000,-10}", val);
    }

    Console.WriteLine()
}

Update: I can use padleft/padright in very simple scenarios, if i have more complicated output it becomes not very concise. Is there something similar to sprintf?

like image 801
homie347 Avatar asked Jan 07 '10 09:01

homie347


People also ask

What C is used for?

C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


2 Answers

Try

double d = 3.14;
Console.WriteLine("{0,10:0.000}", d);

P.S: have a look at this article as a primer on string formatting. Also, string.Format should allow you doing everything sprintf does - and actually more... what else are you trying to do?

like image 171
Paolo Tedesco Avatar answered Sep 22 '22 02:09

Paolo Tedesco


useful

|{0,-10:0.00}| => |87,87 | - With "-" => padRight

|{0,10:0.000}| => | 87,878| - Without "-" => padLeft

|{3,-10:0.###}| - ### - prints numbers after decimal "," only if it is meaningful (not 0): 87,8000 =>87,8

like image 39
batjan Avatar answered Sep 22 '22 02:09

batjan