Domanda

for (int iCount = 0; iCount < oForm.LineItems.Count; iCount++)
           {

// cartDetails is a stringbuilder here.

     cartDetails.Append(String.Format("{0:0}", oForm.LineItems[iCount].Quantity));
     cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].Price));
     cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].ExtendedPrice));

     //cartDetails.Append(string.Format("{0,10:#,##0.00}", oForm.LineItems[iCount].Price) + "</TD><TD>");
     //cartDetails.Append(string.Format("{0,10:#,##0.00}", oForm.LineItems[iCount].ExtendedPrice) + "</TD><TD>");
     //cartDetails.Append(String.Format("{0}", oForm.LineItems[iCount].Quantity).PadLeft(4)+ "</TD><TD>");
     //cartDetails.Append(String.Format("{0:0.00}", oForm.LineItems[iCount].Price).PadLeft(8) + "</TD><TD>");

I have pastd the source code I am using. I add qty, price, extendedprice and all are decimal columns. All I am looking to do is to pad left with leading spaces. Decimal rounding to 2 digits seems to be happening.

Those commented lines above are some of the other options I have tried. Currently if qty has values such as 4 and 40, they don't get aligned when I print them in a table. Same with price.

CAn someone please suggest what am I doing here?

Update1: Tried Lucas suggestion, but it is not working. Here is what I am geting.

cartDetails.Append(String.Format("{0:0,10}", oForm.LineItems[iCount].Quantity));

When I try the above, it shows 10 for every line irrespective of the value in oForm.LineItems[iCount].Quantity.

And if I change String.Format("{0:0,4}", it shows 04 for all the records

È stato utile?

Soluzione 2

Remark: This is for alignemend in caracter based representation such as text files

Have a look at the last section in composite formatting (MSDN).

First format the number as desired and the pad the result

cartDetails.AppendFormat("{0,4}", // padding with spaces
    String.Format("{0:0}", oForm.LineItems[iCount].Quantity));  // format number

Addtition: If you want to position your data in a html table you should use css (or inline styles)

<td class="right">This is right aligned</td>

with css

.right { text-align: right; }

or inlined:

<td style="text-align: right">This is right aligned</td>

Altri suggerimenti

You can use AppendFormat method instead of appending formatted string. Also correct format will be {index,padding:format}. And consider to use foreach instead of for:

foreach (var lineItem in oForm.LineItems)
{ 
    cartDetails.AppendFormat("{0,4:0}", lineItem.Quantity);
    cartDetails.AppendFormat("{0,10:0.00}", lineItem.Price);
    // etc
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top