如果我想稍后更改该字符串的值,但我想保留格式,我该如何向该字符串插入一个值?
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?
我想在文本框中显示订餐的总价。现在,它看起来像“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();
}
}
您应该使用 String.Format Method,正如您在下面的示例中看到的那样:
string s = "1800";
string s = string.Format("{0:#,0.#}", float.Parse(s));
应该是这样的。
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。
我想在文本框中显示订餐的总价。现在,它看起来像“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();
}
}
您应该使用 String.Format Method,正如您在下面的示例中看到的那样:
string s = "1800";
string s = string.Format("{0:#,0.#}", float.Parse(s));
应该是这样的。
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。