验证货币允许超过两位小数

时间:2015-06-12 17:41:44

标签: c# winforms validation currency tryparse

情况:

我正在使用带有.NET4.0的VS2013中的C#编写Winforms应用程序。

数据网格视图中的某些单元格需要验证为格式正确的英国货币值。 dgv单元格格式设置为带两位小数的货币。为了验证,我使用以下代码:

decimal convertedCurrency;

if (decimal.TryParse(dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString(), NumberStyles.Currency, null, out convertedCurrency))
{
    if (convertedCurrency > columnDetails.MaxValue || convertedCurrency < 0)
    {
        this.ReportError(dataGrid, e, dataGrid.Columns[e.ColumnIndex].HeaderText + " must be between £0 and £" + columnDetails.MaxValue);
    }
}
else
{
    this.ReportError(dataGrid, e, "Incorrect format for a money value");
} 

问题:

这完全有效,除非用户输入的值超过两位小数,例如100.001。这被认为是有效的,并且该值被写入数据库。

问题:

如何才能最有效地验证捕获并处理了两位以上小数位的用户输入?我当然可以进入一些凌乱的字符串处理但是有一种更优雅的方式,理想情况下继续使用TryParse吗?

2 个答案:

答案 0 :(得分:1)

我建议三种可能的解决方案:

1)使用MaskedTextBox从一开始就避免问题

2)创建一个keyup事件来解析/检查输入是否正确格式化

3)在输入上使用正则表达式:^ [0-9] 。[0-9] {2} $或^ [0-9] 。[0-9] [0- 9] $

答案 1 :(得分:1)

请参阅Find number of decimal places in decimal value regardless of culture以查找小数位数。只需验证它&lt; = 2。

e.g。

decimal value = 123.456m;
if (GetDecimalPlaces(value) > 2)
{
    // Error
}

int GetDecimalPlaces(decimal d)
{
    int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];
}