范围验证器:货币值不能包含超过两位小数?

4

框架 4.0 Asp.net 应用程序

当我运行代码时,出现了一个错误:“'RangeValidator' 的 MaximumValue 属性的值 '999.9999' 无法转换为类型 'Currency'。”

以下是我的代码:

<asp:RangeValidator Runat='server' ControlToValidate='textEdit' 
    MinimumValue='0.0001'
    MaximumValue='999.9999' Type='Currency' 
    ErrorMessage='Should be between 0.0001 and 999.9999' id="idValidtor" 
 display='None' />

请问货币价值小数点后面不能超过两位吗?如果是,我该如何解决这个问题呢?

1
请发布您用于将货币转换的代码? - Uthistran Selvaraj
<asp:RangeValidator Runat='server' ControlToValidate='textEdit' MinimumValue='0.0001' MaximumValue='999.9999' Type='Currency' ErrorMessage='Should be between 0.0001 and 999.9999' id="idValidtor" display='None' /> - user1118064
1个回答

8
RangeValidator使用NumberFormatInfo.CurrencyDecimalDigits属性来确定字符串是否可以转换为货币,否则将抛出异常。引用自MSDN

当RangeValidator控件的Type属性设置为“Currency”时,必须以NumberFormatInfo.CurrencyDecimalDigits中描述的格式提供MinimumValue和MaximumValue属性,否则将抛出异常。

大多数文化(包括InvariantCulture)的默认值是2(阿拉伯国家为3,但没有4)。因此,您使用的是哪种文化?如果在货币中存储超过两个小数位数很重要,那么您可以在此页面中使用自定义NumberFormatInfo。

protected void Page_PreInit(object sender, EventArgs e)
{
    var customCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
    var nfi = (NumberFormatInfo)customCulture.NumberFormat.Clone();
    nfi.CurrencyDecimalDigits = 4;
    customCulture.NumberFormat = nfi;
    System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
}

(请注意,您需要在顶部添加 using System.Globalization;
(注:该句为提醒,非翻译内容)

感谢您的快速回复。这是我的代码。有没有办法告诉范围验证器,在涉及货币类型时验证最多4个小数点? <asp:RangeValidator Runat='server' ControlToValidate='textEdit' MinimumValue='0.0001' MaximumValue='999.9999' Type='Currency' ErrorMessage='应该在0.0001和999.9999之间' id="idValidtor" display='None' /> - user1118064
@user1118064:我已经编辑了我的答案,展示了如何更改此设置。 - Tim Schmelter
这就是我正在寻找的。非常感谢。它很有效。我已经将其放入HttpModule,Context_BeginRequest中,现在可用于所有站点页面和请求。 - user1118064
刚发现这个答案可以解决我的一个实际工作问题。感谢@TimSchmelter。请注意,对于小数分隔符也是如此。如果您使用逗号作为小数分隔符,则最大值和最小值的常量字符串应反映区域设置。 - Steve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接