【问题标题】:How do i insert a value to a string, if i want to change that string's value later, but i want to keep the format?如果我想稍后更改该字符串的值,但我想保留格式,如何将值插入字符串?
【发布时间】:2019-05-23 16:40:36
【问题描述】:

我想在文本框中显示点餐的总价。现在,它看起来像“1800”,但我想让它看起来像“1.800”。问题是,如果我只是尝试插入一个“。”插入字符串值,则由于总价格可能会发生变化,如果用户订购另一餐,它将不起作用。如果我知道总价可能会发生变化,我该如何保持这种格式?

private void fillTotalCostTextBox()
        {
            textBox_totalPrice.Text = "0";
            foreach (DataGridViewRow row in dataGridView_orders.Rows)
            {
                textBox_totalPrice.Text =
              (Convert.ToInt32(textBox_totalPrice.Text) +
             Convert.ToInt32(row.Cells["price"].Value)).ToString();
            }
        }

【问题讨论】:

  • 首先,循环并汇总您的总数,然后然后使用格式更新您的 TextBox。您的网格是否使用数据源?如果是这样,请遍历它,而不是网格。
  • 然后您可以对textBox_totalPrice.Text = totalAmount.ToString("C");等货币使用字符串格式
  • 将数字存储为数字 (double/int/whathaveyou)。只有当您显示/打印它们时,您才需要格式化它们。这样你就可以合计它们,修改值等。
  • 谢谢你们,这是关键。 对价格求和之后进行格式化。

标签: c# string winforms textbox


【解决方案1】:

您应该使用String.Format Method,如下面的示例所示:

string s = "1800";
string s = string.Format("{0:#,0.#}", float.Parse(s));

【讨论】:

    【解决方案2】:

    应该是这样的。

    private void fillTotalCostTextBox()
    {
      decimal totalPrice = 0;
      foreach (DataGridViewRow row in dataGridView_orders.Rows)
      {
        totalPrice += Convert.ToDecimal(row.Cells["price"].Value)).ToString();
      }
      textBox_totalPrice.Text = string.format("{0:#.00}", totalPrice);
    }
    

    如果要显示货币值,可以使用 C (string.format("C2", totalPrice))。只需确保检查单元格值中的空值或使用 TryCast。

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多