Originally Posted by

**Dave_Sinkula**
Why not just learn how to use

strtod? Consider also something like

"+1.234E-05".

well strtod has made my number checking easy.and with less line of codes .

I have added an extra function (checkNumber) in my code which basically do the same as the previous isNumber function .

Code:

#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
char errorNum[20]="";
char tempVal[100]="";
int isNumber(char str[])
{
int withDecimal =0,isNegative=0 ,i=0;
int len = strlen(str);
for (i=0; i<len; i++)
{
if (!isdigit(str[i])) // if1
{
if (str[i] == '.')
{
if(len!=1 && str[i+1] != '-')
{
if(withDecimal){
return 0;
}
withDecimal =1;
}else{
return 0;
}
}
else if (str[i] == '-')
{
if(len!=1){
if(str[i+1] == '.')
{
if(isdigit(str[i+2])){
if(isNegative){
return 0;
}
if(i==0){
isNegative = 1;
}else{
return 0;
}
}else{
return 0;
}
}
}else{
return 0;
}
}else{
return 0;
}
} //end if1
}// end for
return 1;
}
int checkNumber(char str[]){
char *ok;
ok = str;
if(strlen(ok)==0){
return 1;
}else{
return 0;
}
}
int main(){
//for testing purpose only
char charNum[10][15] = {
"100.23" ,
"-200.456",
"0.0",
"-..30",
".-",
"-.65",
"-0.54",
"0",
".",
"+1.234E-05"
};
int cntr = 0;
for(cntr=0; cntr<10; cntr++){
printf("%s\t\t", charNum[cntr]);
if(isNumber(charNum[cntr])){
printf("is a number!\n");
}else{
printf("NOT a NUMBER!\n");
}
}
printf("\n=================================\n\n");
for(cntr=0; cntr<10; cntr++){
printf("%s\t\t", charNum[cntr]);
if(checkNumber(charNum[cntr])){
printf("is a number!\n");
}else{
printf("NOT a NUMBER!\n");
}
}
}

OUTPUT

Code:

100.23 is a number!
-200.456 is a number!
0.0 is a number!
-..30 NOT a NUMBER!
.- NOT a NUMBER!
-.65 is a number!
-0.54 is a number!
0 is a number!
. NOT a NUMBER!
+1.234E-05 NOT a NUMBER!
=================================
100.23 is a number!
-200.456 is a number!
0.0 is a number!
-..30 NOT a NUMBER!
.- NOT a NUMBER!
-.65 is a number!
-0.54 is a number!
0 is a number!
. NOT a NUMBER!
+1.234E-05 is a number!

I haven't add any error checking in strtod() but as you can see, the function that uses strtod is clearly accurate.

I'm not really familiar with the memory comsumption and portability by these function.

So the question now is which of the two, isdigit() or strtod() is portable?

and also between the two function checkNumber() and isNumber(), which is best to use, in terms of memory consumption.

regards,

jaro