Hi to all!,
I have a function that convert a string numeral (entered by a user) to a double value, having rounded its decimal value to (in this case) 4 significant places.
here is the code
Code:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int isNumber(const char str[])
{
char *ok;
strtod(str,&ok);
return !isspace(*str) && strlen(ok)==0;
}
double stringToDouble(char *digit , size_t decPlace) // int dec is the number of decimal places
{
double result = 0;
char *ptr;
char temp1[10]="";
char temp2[15]="";
if(digit != NULL && isNumber(digit)) // check if string is not NULL and a valid number
{
result = strtod(digit,&ptr);
sprintf(temp1,"%%.%df",decPlace);
sprintf(temp2,temp1,result);
result = strtod(temp2,&ptr);
}else
{
printf("FAILED:The String (%s) cannot be converted to double: result -> %g\n",digit, result);
}
return result;
}
int main()
{
double num ;
char numberInString[100];
int decPlace = 4;
//for testing purpose only
printf("Enter a number\n");
fgets(numberInString, sizeof(numberInString), stdin);
if (numberInString[strlen(numberInString)-1] == '\n')
{
numberInString[strlen(numberInString)-1] = '\0';//remove the new-line
}
printf("the string %s\n",numberInString);
num =stringToDouble(numberInString,decPlace);
printf("is converted to double with value of %f with %d significant decimal places\n",num,decPlace);
return 0;
}
OUTPUT
Enter a number
34.56789
the string 34.56789
is converted to double with value of 34.567900 with 4 significant decimal places
My question is with regards to stringToDouble().
I've used two temporary character array, temp1 and temp2 respectively, in order to manipulate the output of stringToDouble
in order for the stringToDouble to return the right value (with decimal place included).
Does this solution valid?
strtod() only returns the string in double form.AFAIK it can't round off value (decimal places).
Regards,
jaro