Validating currency allows more than two decimal places

784 views Asked by At

Situation:

I'm writing a Winforms app using C# in VS2013 with .NET4.0.

Some cells in a datagridview need to be validated as correctly formatted UK currency values. The dgv cell format is set to currency with two decimal places. For validation I'm using the following code:

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");
} 

Issue:

This works prefectly except if the user inputs a value with more than two decimal places e.g. 100.001. This is deemed valid and this value is written to the database.

Question:

How can I best validate such that user input with more than two decimal places caught and handled? I could of course get into some messy string handling but is there a more ellegant way, ideally continuing to use TryParse?

2

There are 2 answers

0
Jared Moore On BEST ANSWER

See Find number of decimal places in decimal value regardless of culture to find the number of decimal places. Just verify that it's <= 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];
}
0
SteveFerg On

Three possible solutions I would suggest:

1) Use a MaskedTextBox to avoid the problem from the start

2) Create a keyup event to parse/check the input for correct formatting

3) use regex on the input: ^[0-9].[0-9]{2}$ or ^[0-9].[0-9][0-9]$