I have a GridView and it is programmatically bound a to a List<T>
where T is a custom object of mine, say, OrderItem
. The decimal type values display many decimal places. I want to round them off to just 2 decimal places. How do I do that?
Here's roughly what I have:
public class OrderItem
{
public Product Product { get; set; }
public int Quantity { get; set; }
public decimal GrossAmount { get; set; }
}
public class Product
{
public string ProductName { get; set; }
public decimal Price { get; set; }
public decimal DiscountPercent { get; set; }
}
<asp:GridView ID="dgOrderItems" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText = "Product">
<ItemTemplate>
<%# Eval("Product.ProductName") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Price">
<ItemTemplate>
<%# Eval("Product.Price") %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "Quantity" HeaderText = "Quantity" />
<asp:BoundField DataField = "GrossAmount" HeaderText = "Gross Amount" />
<asp:TemplateField HeaderText = "Discount (%)">
<ItemTemplate>
<%# Eval("Product.DiscountPercent") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Use the formatting available in Eval on TemplateFields, ie:
<%# Eval("Product.Price", "{0:C}") %>
For Bound Fields use the BoundField.DataFormatString Property , ie:
<asp:BoundField DataField="GrossAmount"
HeaderText="Gross Amount"
DataFormatString="{0:f2}" />
See Standard Numeric Format Strings for the formatting strings you can use.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.