2016-05-16 91 views
2

我使用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

回答

1

我試着使用小數,但它也沒」牛逼正常工作,所以我用我自己計算出的總價格的一些事情,如:

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; 

} 

非常感謝您的幫助:)

0

@Ksib提供了一個關於使用decimal代替double的好處。十進制會給你更多的精度。此外,將價格表示爲數字字符串和格式作爲貨幣。有關詳細說明,請參閱MSDN decimaldouble條目中的註釋。 MSDN的數字格式信息是here

0

如果以下內容不改變數據的查看方式,那麼您必須更改視圖本身。

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

問題是int.parse。不管那是什麼會返回一個整數。嘗試使用Kentico ValidationHelper類,並獲得雙精度或十進制值,或者您可以使用您使用以上decimal.parse相同的語法等

+0

'int.parse()'被用於'GetShoppingCartItemInfo()',而不是實際的數學部分。 –

+0

正是......所以它會自動給你12做你的數學,而不是11.5。 – Josh

+0

你不明白'GetShoppingCartItemInfo()'的作用。這就像訪問一個數組。 'int.Parse(row [「CartItemID」] .ToString())'只是取得該項目的ID並將其變成一個'int'而不是貨幣值。 –