范围验证器 货币值不能包含小数点后超过 2 位数字?



Framework 4.0 Asp.net 应用程序

当我运行代码时,我收到一个错误"'范围验证器'的最大值属性的值'999.9999'无法转换为'货币'类型。

下面是我的代码:

<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' />

请解释一下货币价值不能包含小数点后超过 2 位数字?除非我如何解决此问题?

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

当范围验证程序控件的 Type 属性设置为 "货币",最小值和最大值属性必须是 以类似于中所述的格式提供 NumberFormatInfo.CurrencyDecimalDigits,否则例外是 扔了

大多数区域性的默认值(包括 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;

最新更新