kknaguib
kknaguib

Reputation: 749

C#: Min to max number of digits after a decimal

I'm trying to do a check for a user input for the rate entered, I want to accept the value entered if it has min 2 digits to a max of 5 digits after the decimal.

Valid Example:

*1.12
*1.123
*1.1234
*1.12345

Not Valid:

1
1.1
1.123456

etc.

I've been trying to get it with Regex but right now it only allows only 5 digits after the decimal nothing less nothing more. Here's the code:

//Check if the string is a double 
bool IsDouble(string s)
{
    var regex = new Regex(@"^\d+\.\d{5}?$");
    var check = regex.IsMatch(s);
    return check;  
}

A little help would be greatly appreciated.

Upvotes: 0

Views: 1280

Answers (4)

paparazzo
paparazzo

Reputation: 45096

A non-regex solution
It also returns the decimal

public int? DecimalAfter (string strDec, out decimal? decNull)
{
    int? decAfter = null;
    strDec = strDec.Trim();
    decimal dec;
    if (decimal.TryParse(strDec, out dec))
    {
        decNull = dec;
        int decPos = strDec.IndexOf('.');
        if (decPos == -1)
        {
            decAfter = 0;
        }
        else
        {
            decAfter = strDec.Length - decPos - 1;
        }
    }
    else decNull = null;

    return decAfter;
}

Upvotes: 0

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28413

Try this Regex

you can specify your own range here d{2,5}

^\s*-?[1-9]\d*(\.\d{2,5})?\s*$

(Or)

^(\d{1,5}|\d{0,5}\.\d{2,5})$

REGEX DEMO

Upvotes: 0

D Stanley
D Stanley

Reputation: 152594

Use the pattern

"^\d+\.\d{2,5}?$"

to match between 2 and 5 characters

Upvotes: 1

Patrick Quirk
Patrick Quirk

Reputation: 23757

This should do it:

^\d+\.\d{2,5}$

Upvotes: 2

Related Questions