C# 肯迪科的购物车总价问题
我正在使用Kentico API在我的网站上显示我的产品,但在显示购物车的总价格时,我遇到了一个问题。它自动循环-如果价格为11.5,则为12 以下是我返回总价的方法:C# 肯迪科的购物车总价问题,c#,kentico,C#,Kentico,我正在使用Kentico API在我的网站上显示我的产品,但在显示购物车的总价格时,我遇到了一个问题。它自动循环-如果价格为11.5,则为12 以下是我返回总价的方法: public double GetTotalShoppingCart(int userID, string siteName) { double totalPrice=0.0; ShoppingCartInfo cartInfo = GetShopCard(userID, site
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;
}
只有当它是整数或实数时,它才会返回正确的总价,但如果它包含任何分数,它会将其四舍五入到最高数字。您知道问题的原因吗?@Ksib提出了一个关于使用
十进制
代替双精度
的好观点。十进制将给你更高的精度。另外,将价格表示为数字字符串,格式表示为货币。有关详细说明,请参见MSDN和条目中的备注。MSDN的数字格式信息为。如果以下内容未更改数据的查看方式,则必须更改视图本身
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等相同的语法。我尝试使用decimal,但它也无法正常工作,因此我自己计算了总价,例如:
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;
}
非常感谢您的帮助:)当您调试时是
totalPrice
11.5还是12?如果是11.5,那么我想知道您是否可以修改视图,使其显示正确的小数位数?另外,您选择double而不是decimal有什么原因吗?int.parse()
用于GetShoppingCartItemInfo()
,而不是实际的数学部分。准确地说……因此它会自动为您提供12而不是11.5进行数学运算。您不理解GetShoppingCartItemInfo()
的功能。这就像访问一个数组int.Parse(row[“CartItemID”].ToString())
只是获取项目的ID并将其转换为int
而不是货币值。