如何覆盖 ASP.NET Web 应用程序当前区域性的货币格式?

问题描述 投票:0回答:3

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 = ","; }

但是,如何为应用程序从此时开始处理的所有请求激活新区域性?还有其他方法可以实现我想做的事情吗?

.net asp.net internationalization formatting cultureinfo
3个回答
3
投票
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;



0
投票
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); } }

我稍后会发表一篇文章,其中包含所有血淋淋的细节。


0
投票

我最终编写了一个

IIS 模块

,无需编辑代码即可覆盖主机货币、数字和日期/时间格式(由主机服务器的区域设置决定)。 它可以自定义货币符号、小数分隔符、数字组分隔符、长日期格式、短日期格式...基本上所有可以通过 .NET 中的 NumberFormatInfo 和 DateTimeFormatInfo 对象显式设置的属性。全部通过 web.config 文件完成(即:无需更改代码)。

希望这可以节省一些人的时间和/或挫败感。

© www.soinside.com 2019 - 2024. All rights reserved.