I was working on a .NET website and wanted to write some C# code to validate that a value input by the user was numeric and had at most two decimal places. This is useful, for example, when validating that the input represents a dollar amount.

I first tried this, which didn't work:

try

{

// must be numeric value

double d = double.Parse(s);

// max of two decimal places

if (100 * d != (int)(100 * d)) // max of two decimal places

return false;

return true;

}

catch

{

return false;

}

The above is unreliable because, since d is a floating-point number, 100 * d isn't always exactly equal to (int)(100 * d), even when d has two or fewer decimal places. For example, 100 * 1.23 might evaluate to, say, 122.9999999.

This post on StackOverflow offers several solutions, but none of them looked right for my purpose. Instead, I came up with this:

try

{

// must be numeric value

double d = double.Parse(s);

// max of two decimal places

if (s.IndexOf(".") >= 0)

{

if (s.Length > s.IndexOf(".") + 3)

return false;

}

return true;

catch

{

return false;

}

The same thing could be accomplished using a regular expression, if you prefer.

## No comments:

## Post a Comment