GridView单元格中的舍入值

时间:2012-09-24 14:53:20

标签: c# asp.net gridview

我有一个GridView,它以编程方式绑定到List<T>,其中T是我的自定义对象,比如OrderItem。十进制类型值显示许多小数位。我想将它们四舍五入到小数点后两位。我该怎么做?

这大致是我所拥有的:

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>

1 个答案:

答案 0 :(得分:5)

使用TemplateFields上的Eval中可用的格式,即:

<%# Eval("Product.Price", "{0:C}") %>

对于Bound Fields,使用BoundField.DataFormatString Property,即:

<asp:BoundField DataField="GrossAmount" 
                HeaderText="Gross Amount" 
                DataFormatString="{0:f2}" />

有关您可以使用的格式化字符串,请参阅Standard Numeric Format Strings