我如何根据用户输入舍入我的价值?

how can i round off my value based on user input?

我的 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) overload 来指定您的 MidpointRoundingAwayFromZeroToEvenToEven 是默认选项。

当您想要转换 string 时,最好的方法是使用 CurrencyFormat。您可以使用以下代码:

txtTotalPrice.Text = TotalPrice.ToString("C"); 
txtTotalProducts.Text = TotalProducts.ToString("C");

而不是:

txtTotalPrice.Text = Convert.ToString(TotalPrice);
txtTotalProducts.Text = Convert.ToString(TotalProducts);