Kentico 购物车总价问题

Shopping cart total price problems in Kentico

我正在使用 Kentico API 在我的网站上展示我的产品,但我在展示购物车总价时遇到了问题。它会自动舍入 - 如果价格为 11.5,则为 12。

这是我return总价的方法:

    public double GetTotalShoppingCart(int userID, string siteName)
    {
        double totalPrice=0.0;
        ShoppingCartInfo cartInfo = GetShopCard(userID, siteName);
        int siteID = GetSite(siteName);
        if (cartInfo != null)
        {
            DataSet cartItems = ShoppingCartItemInfoProvider.GetShoppingCartItems(cartInfo.ShoppingCartID);
            if (cartItems.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in cartItems.Tables[0].Rows)
                {
                    totalPrice += ShoppingCartItemInfoProvider.GetShoppingCartItemInfo(int.Parse(row["CartItemID"].ToString())).TotalPrice;   
                }
            }
        }
        return totalPrice;
    }

它 return 仅当它是整数或实数时才是正确的总价,但如果它包含任何小数,它会四舍五入到最高数字。你知道是什么导致了这个问题吗?

@Ksib 提出了一个关于使用 decimal 代替 double 的好观点。十进制会给你更多的精度。此外,将价格表示为数字字符串,将格式表示为货币。参见MSDN中的备注decimal and double entries for a detailed explanation. MSDN's numeric formatting info is here.

如果以下内容没有改变数据的查看方式,那么您将不得不更改视图本身。

public decimal GetTotalShoppingCart(int userID, string siteName)
{
    decimal totalPrice = 0;
    ShoppingCartInfo cartInfo = GetShopCard(userID, siteName);
    // Not sure what siteID is used for here...
    int siteID = GetSite(siteName);
    if (cartInfo != null)
    {
        if (cartItems.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow row in cartItems.Tables[0].Rows)
            {
                totalPrice += (decimal)ShoppingCartItemInfoProvider.GetShoppingCartItemInfo(int.Parse(row["CartItemID"].ToString())).TotalPrice;   
            }
        }
    }
    return totalPrice;
}

问题是int.parse。不管那是要 return 一个整数。尝试使用 Kentico ValidationHelper class 并获取双精度或十进制值,或者您可以使用上面与 decimal.parse 等相同的语法。

我试过使用 十进制 但它也没有正常工作所以我自己计算了总价,比如:

public decimal GetTotalShoppingCart(int userID, string siteName)
{
    decimal totalPrice=0;
    ShoppingCartInfo cartInfo = GetShopCard(userID, siteName);
    int siteID = GetSite(siteName);

    if (cartInfo != null)
    {
        DataSet cartItems = ShoppingCartItemInfoProvider.GetShoppingCartItems(cartInfo.ShoppingCartID);
    if (cartItems.Tables[0].Rows.Count > 0)
    {
        foreach (DataRow row in cartItems.Tables[0].Rows)
        {
            totalPrice += decimal.Parse(row["SKUUnits"].ToString()) * decimal.Parse(row["SKUPrice"].ToString());//(decimal)ShoppingCartItemInfoProvider.GetShoppingCartItemInfo(int.Parse(row["CartItemID"].ToString())).TotalPrice;   
        }
    }
}
return totalPrice;

}

非常感谢您的帮助:)