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()) return false;
if(cstrValue.Find(_T(".")) == -1) return false;
std::string strValue, strChar;
int nDotNum = 0;
strValue.assign ((std::string)(LPCSTR) cstrValue.GetString ());
if(strValue.find_first_not_of("1234567890.-") != string::npos)
return false;
for(int i = 1; i < cstrValue.GetLength(); i++)
{
if(isalpha(cstrValue.GetAt(i)))
return false;
strChar = cstrValue.GetAt(i);
if((strValue.compare(".") == 0) && (strValue.compare(strChar) == 0))
return false;
if(strChar.compare(".") == 0)
{
nDotNum++;
if(nDotNum > 1)
return false;
}
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.