Kentico中的购物车总价问题

问题描述:

我使用Kentico API在我的网站上显示我的产品,但我在显示总购物车价格时遇到问题。它会自动四舍五入 - 如果价格是11.5它使12Kentico中的购物车总价问题

这里是我的方法返回总价:

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; 
    } 

它返回,只有当它是一个整数或实数正确的总价格,但如果它包含任何分数,则将其舍入到最高数字。你知道是什么导致了这个问题?

+0

当你调试'totalPrice' 11.5或12?如果它是11.5,那么我不知道你是否可以修改视图,以便它显示正确的小数位数可能?另外,是否有你选择双精度而不是小数的原因? – KSib

我试着使用小数,但它也没”牛逼正常工作,所以我用我自己计算出的总价格的一些事情,如:

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; 

} 

非常感谢您的帮助:)

@Ksib提供了一个关于使用decimal代替double的好处。十进制会给你更多的精度。此外,将价格表示为数字字符串和格式作为货币。有关详细说明,请参阅MSDN decimaldouble条目中的注释。 MSDN的数字格式信息是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。不管那是什么会返回一个整数。尝试使用Kentico ValidationHelper类,并获得双精度或十进制值,或者您可以使用您使用以上decimal.parse相同的语法等

+0

'int.parse()'被用于'GetShoppingCartItemInfo()',而不是实际的数学部分。 –

+0

正是......所以它会自动给你12做你的数学,而不是11.5。 – Josh

+0

你不明白'GetShoppingCartItemInfo()'的作用。这就像访问一个数组。 'int.Parse(row [“CartItemID”] .ToString())'只是取得该项目的ID并将其变成一个'int'而不是货币值。 –