65.9K
CodeProject is changing. Read more.
Home

Validation for Decimal Number

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.44/5 (4 votes)

Aug 17, 2015

CPOL

1 min read

viewsIcon

20295

Validate whether value in string is a valid decimal number or not.

Introduction

Many times, we come across a situation when we require to validate whether the text in string is a valid decimal number or not.

In C/C++, there is no inbuilt function to do that, so the only thing we come across is to write a validation logic for it, covering all possible cases of validating as a decimal number.

Explanation

This article explains how to validate a text for decimal number. For a decimal numer, we require to have that a number starts with a digit, dot ('.'), or minus ('-').

It is compulsory to have a dot ('.') in a text for a decimal value. Minus is used as a decimal number and can be a signed number also.

Sign decimal numbers, like -2.3, -0.3 can have minus sign at first position only.

A decimal number can start with dot also, like .34, -.12, so dot also can be at the first position. But a decimal number should have only one dot.

There should not be any alphabetic or special characters. Alphabetic characters can be checked using function isalpha() as shown below:

int isalpha ( int c );

For reference, the code snippet to validate a text as a decimal value, is as given below:

bool ValidateDecimalNumber(CString cstrValue)
{
    if(cstrValue.IsEmpty())  //String should not be empty
        return false;

    if(cstrValue.Find(_T(".")) == -1)  //String should contain '.' compulsory 
        return false;

    std::string strValue, strChar;
    int nDotNum = 0;

    //Validating first character
    strValue.assign ((std::string)(LPCSTR) cstrValue.GetString ());
    if(strValue.find_first_not_of("1234567890.-") != string::npos)
        return false;

    //Loop starts with second character, as first character is already validated above
    for(int i = 1; i < cstrValue.GetLength(); i++)
    {
        //Checking against alpabetic characters
        if(isalpha(cstrValue.GetAt(i)))
            return false;

        strChar = cstrValue.GetAt(i);
      
        //Checking if dot is there as first character, then should not be there again
        if((strValue.compare(".") == 0) && (strValue.compare(strChar) == 0))
            return false;

        //Checking if dot is not there at first position, then should not be more than one
        if(strChar.compare(".") == 0)
        {
            nDotNum++;
            if(nDotNum > 1)
                return false;
        }

        //Checking against special and other characters
        if(strChar.find_first_of("~`!@#$%^&*()_+={}\\|':;?/><,\"-") != string::npos)
            return false;
    }
    return true;
}

Points of Interest

The above code can be optimized further. Suggestions are always welcome.