【问题标题】:Validating currency allows more than two decimal places [duplicate]验证货币允许多于两位小数[重复]
【发布时间】:2015-06-12 17:41:44
【问题描述】:

情况:

我正在用 .NET4.0 在 VS2013 中使用 C# 编写一个 Winforms 应用程序。

datagridview 中的某些单元格需要验证为格式正确的英国货币值。 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?

【问题讨论】:

  • 请参阅stackoverflow.com/questions/13477689/… 以查找小数位数。只需验证它是
  • 真的很有帮助@JaredMoore。如果这是答案而不是 cmets,我会支持你。
  • 干杯,转换为答案。

标签: c# winforms validation currency tryparse


【解决方案1】:

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

例如

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

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 1970-01-01
      • 2016-04-20
      • 2022-01-26
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多