en-ZA 区域的货币小数点和千位分隔符分别为“,”和“ ”,但常用的分隔符为“.”。对于十进制,加上我的用户想要“,”作为千位分隔符。我希望全局设置这些,这样我只需对所有货币字段使用
{0:C}
格式字符串,而无需任何显式 Format
或 ToString
调用。
我希望能够在不更改网络服务器上的区域性设置的情况下执行此操作,因为我还需要将货币的小数位设置为零,因为在报告 R100k 及以上的估计值等时不需要美分。不想任意将整个区域性设置为零,仅针对此应用程序设置一个。
在对“这个问题”的回答的评论中,Jon Skeet 建议克隆当前的文化和设置并更改所需的设置。我已经这样做了:
void Application_Start(object sender, EventArgs e)
{
var newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
newCulture.NumberFormat.CurrencyDecimalSeparator = ".";
newCulture.NumberFormat.CurrencyGroupSeparator = ",";
}
但是,如何为应用程序从此时开始处理的所有请求激活新区域性?还有其他方法可以实现我想做的事情吗?
Application_BeginRequest
事件为每个请求设置区域性。内部活动:
var newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
newCulture.NumberFormat.CurrencyDecimalSeparator = ".";
newCulture.NumberFormat.CurrencyGroupSeparator = ",";
System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;
BoundField
并提供您自己的
FormatProvider
:public class BoundReportField : BoundField
{
protected virtual string GetDefaultFormatString(FieldFormatTypes formatType)
{
var prop = typeof(FormatStrings).GetProperty(formatType.ToString()).GetValue(null, null);
return prop.ToString();
}
protected virtual IFormatProvider GetFormatProvider(FieldFormatTypes formatType)
{
var info = (CultureInfo)CultureInfo.CurrentCulture.Clone();
info.NumberFormat.CurrencyDecimalDigits = 0;
info.NumberFormat.CurrencySymbol = "R";
info.NumberFormat.CurrencyGroupSeparator = ",";
info.NumberFormat.CurrencyDecimalSeparator = ".";
return info;
}
private FieldFormatTypes _formatType;
public virtual FieldFormatTypes FormatType
{
get { return _formatType; }
set
{
_formatType = value;
DataFormatString = GetDefaultFormatString(value);
}
}
protected override string FormatDataValue(object dataValue, bool encode)
{
// TODO Consider the encode flag.
var formatString = DataFormatString;
var formatProvider = GetFormatProvider(_formatType);
if (string.IsNullOrWhiteSpace(formatString))
{
formatString = GetDefaultFormatString(_formatType);
}
return string.Format(formatProvider, formatString, dataValue);
}
}
我稍后会发表一篇文章,其中包含所有血淋淋的细节。