如何根据用户输入来取整我的价值
本文关键字:我的 何根 用户 输入 | 更新日期: 2023-09-27 18:01:10
我的updatetobill代码中有这段代码。我想我打算四舍五入到最接近的十分之一?例如,价格是123456.123456,我想做的是将其作为123456.12,因为这是一个价格,我需要美分。提前感谢您的帮助:(
private void UpdateTotalBill()
{
double vat = 0;
double TotalPrice = 0;
long TotalProducts = 0;
foreach (DataListItem item in dlCartProducts.Items)
{
Label PriceLabel = item.FindControl("lblPrice") as Label; // get price
TextBox ProductQuantity = item.FindControl("txtProductQuantity") as TextBox; // get quantity
double ProductPrice = Convert.ToInt64(PriceLabel.Text) * Convert.ToInt64(ProductQuantity.Text); //computation fro product price. price * quantity
vat = (TotalPrice + ProductPrice) * 0.12; // computation for total price. total price + product price
TotalPrice = TotalPrice + ProductPrice+40 +vat;
TotalProducts = TotalProducts + Convert.ToInt32(ProductQuantity.Text);
}
Label1.Text = Convert.ToString(vat);
txtTotalPrice.Text = Convert.ToString(TotalPrice); // put both total price and product values and converting them to string
txtTotalProducts.Text = Convert.ToString(TotalProducts);
}
像Math.Round
一样四舍五入;
Math.Round(TotalPrice, 2) // 123456.12
您也可以使用Math.Round(Double, Int32, MidpointRounding)
重载来指定您的MidpointRounding
是AwayFromZero
或ToEven
。ToEven
是默认选项。
当您想要转换string
时,最好的方法是使用CurrencyFormat
。您可以使用以下代码:
txtTotalPrice.Text = TotalPrice.ToString("C");
txtTotalProducts.Text = TotalProducts.ToString("C");
相反:
txtTotalPrice.Text = Convert.ToString(TotalPrice);
txtTotalProducts.Text = Convert.ToString(TotalProducts);