The simplest solution would be checking the string (the characters) when the number is entered (as stated in the question):
bool bResult = (*input != 0);
int decPoint = 0;
while (bResult && *input)
{
switch (*input)
{
case '.' : decPoint++;
case '0' :
case '1' : break;
default : bResult = false;
}
input++;
}
if (decPoint != 1)
bResult = false;
Converting the input to a floating point value will not work because those can not represent real number in most cases.
For example the value 1.0011 is represented internally as 0x3F80240B with single precision upon conversion (e.g. when using
atof()
). Printing this out with full precision it will be 1.00109994.
For double precision it will be 0x3FF004816F0068DC which is 1.0011000000000001.
You mentioned that you are already able to check the integer part. This can be also used for the fractional part by just treating that as integer too:
Locate the decimal point using
strchr()
, pass the returned pointer plus one to the conversion function
atoi()
and perform the same check as for the integer part.