Mike
Mike

Reputation: 3294

How to validate a decimal number to have precision exactly one?

I need to validate user input into a textbox to be a decimal number of precision exactly one? For example below are some of the cases..

How can I achieve this using C#(.net 3.5)?

Its a WPF textbox.

Thanks, -Mike

Upvotes: 0

Views: 2699

Answers (3)

Jamie Kelly
Jamie Kelly

Reputation: 309

For a non-regex way of achieving this:

string input;
decimal deci;
if (input.Length >=3 && input[input.Length - 2].Equals('.') && Decimal.TryParse(input , out deci))
{
    // Success
}
else
{
    // Fail
}

Upvotes: 2

Rohit Vyas
Rohit Vyas

Reputation: 1969

Yes regular expression is the best way to check your condition:

For exactly NNNN.N (1234.5) use:

/^\d{4}\.\d$/

For optional .N (1234 1234. 1234.5) go with:

/^\d{4}(\.\d?)?$/

For numbers up to size of NNNN.N (1 .5 12.5 123. 1234 1234.5) go with:

/^(?=.*\d)\d{0,4}(\.\d?)?$/

And if you want to allow +/- at the beginning, then replace ^ with ^[-+]?.

Upvotes: 0

christopher
christopher

Reputation: 27356

Easiest way, to me, seems to be to use regular expressions. By interpreting the user input as a string, you can compare it with something like '[0-9]+\.[0-9]'

Upvotes: 2

Related Questions