下面的代码允许一个值通过,如"349.99"进入计算。我现在遇到的唯一问题是,在 TotalPrice 文本框中填充的最终值仍然四舍五入到最接近的整数。
对以下代码进行的最佳更改是什么,以防止这种情况。我正在使用它来计算账单,所以希望值为"239.39"等?
干杯千斤顶
UpdateTotalBill()
{
long TotalPrice = 0;
long TotalProducts = 0;
foreach (DataListItem product in dlBasketItems.Items)
{
Label PriceLabel = product.FindControl("lblProductPrice") as Label;
TextBox ProductQuantity = product.FindControl("txtProductQuantity") as TextBox;
long ProductPrice;
{
ProductPrice = Convert.ToInt64(PriceLabel.Text) *
Convert.ToInt64(ProductQuantity.Text);
}
TotalPrice = TotalPrice + ProductPrice;
TotalProducts = TotalProducts + Convert.ToInt32(ProductQuantity.Text);
}
txtTotalPrice.Text = Convert.ToString(TotalPrice);
txtTotalProducts.Text = Convert.ToString(TotalProducts);
}
你的变量类型很长,你也使用 Convert.ToInt64...这是你丢失数字小数部分的两个地方。
因此,您应该拥有decimal
变量并改用Convert.ToDecimal
。
{
decimal TotalPrice = 0.0;
decimal TotalProducts = 0.0;
foreach (DataListItem product in dlBasketItems.Items)
{
Label PriceLabel = product.FindControl("lblProductPrice") as Label;
TextBox ProductQuantity = product.FindControl("txtProductQuantity") as TextBox;
decimal ProductPrice = Convert.ToDecimal(PriceLabel.Text) *
Convert.ToInt32(ProductQuantity.Text);
TotalPrice = TotalPrice + ProductPrice;
TotalProducts = TotalProducts + Convert.ToInt32(ProductQuantity.Text);
}
txtTotalPrice.Text = Convert.ToString(TotalPrice);
txtTotalProducts.Text = Convert.ToString(TotalProducts);
}
在原始示例中,还混合了 Convert.ToDecimal/Int64/Int32 进行 txtproductQuantity 转换。您可能希望在此字段中只允许整数,因此您可以仅使用 Convert.ToInt32(甚至可能更小的类型,具体取决于您的数字)