String.Format相同代码不同视图
我有这样的代码;
GridView1.FooterRow.Cells[11].Text = String.Format("{0:c}", sumKV)
在我的计算机中,这段代码给出了这样的结果;
但是,当我将此代码上传到我的虚拟机时,它看起来像这样;
TL意为土耳其里拉。 但我不想显示货币。 我只想要数字。
我也不想改变数字格式。 (如257.579,02)
我怎样才能在此代码中删除TL ?
我会用这个:
var cultureWithoutCurrencySymbol = (CultureInfo)CultureInfo.CurrentCulture.Clone(); cultureWithoutCurrencySymbol.NumberFormat.CurrencySymbol = ""; GridView1.FooterRow.Cells[11].Text = String.Format(cultureWithoutCurrencySymbol, "{0:c}", sumKV).Trim();
背景:
这仍将保留当前文化的货币格式,它只是删除货币符号。
您可以在某处保存这种特殊文化,因此您无需在每次需要格式化值时创建它。
更新:
- 现在它甚至编译…… 😉
- 添加了
Trim()
,因为在格式化数字之后仍有空格。
另一种选择是完全关闭当前线程的货币符号:
private static NumberFormatInfo SetNoCurrencySymbol() { CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone(); NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); NumberFormatInfo ret = culture.NumberFormat; LocalFormat.CurrencySymbol = ""; culture.NumberFormat = LocalFormat; // Add the culture to the current thread Thread.CurrentThread.CurrentCulture = culture; return ret; }
这样你就可以改变更少的代码。 您可以随后将其更改回来:
NumberFormatInfo origNumberFormat = SetNoCurrencySymbol(); string x = String.Format("{0:c}", 55); CultureInfo.CurrentCulture.NumberFormat = origNumberFormat; string y = String.Format("{0:c}", 55);
因为您只使用带有格式字符串的String.Format,所以sumKV的格式根据应用程序中实际使用的UI Culture。
GridView1.FooterRow.Cells[11].Text = String.Format("{0:c}", sumKV),
要摆脱货币符号,请使用String.Format
InvariantCulture:
String.Format(CultureInfo.InvariantCulture, "{0:c}", sumKV);
如果您不想显示货币,请不要使用货币格式代码 – {0:c}。 也许尝试以下内容:
GridView1.FooterRow.Cells[11].Text = String.Format("{0:G}", sumKV);
看到这篇文章 – String.Format加倍