converts a string of digits into a double type number. - C String

C examples for String:String Function

Description

converts a string of digits into a double type number.

#include <ctype.h>

double atof(char str[])
{
  double value, power;
  int j, sign;
  for(j = 0; isspace(str[j]); j++)
    ;                                                /* null statement */
  sign = (str[j] == '-') ? -1 : 1;
  if(str[j] == '+' || str[j] == '-')
    j++;
  for(value = 0.0; isdigit(str[j]); j++)
    value = 10.0 * value + (str[j] - '0');
  if(str[j] == '.')
    j++;
  for(power = 1.0; isdigit(str[j]); j++){
    value = 10.0 * value + (str[j] - '0');
    power = power * 10.0;
  }
  return sign * value / power;
}

Demo Code

#include <stdio.h>

#include <ctype.h>

double atof(char str[])
{
  double value, power;
  int j, sign;/*from w w w  . j  av  a 2 s  . co  m*/
  for(j = 0; isspace(str[j]); j++)
    ;                                                /* null statement */
  sign = (str[j] == '-') ? -1 : 1;
  if(str[j] == '+' || str[j] == '-')
    j++;
  for(value = 0.0; isdigit(str[j]); j++)
    value = 10.0 * value + (str[j] - '0');
  if(str[j] == '.')
    j++;
  for(power = 1.0; isdigit(str[j]); j++){
    value = 10.0 * value + (str[j] - '0');
    power = power * 10.0;
  }
  return sign * value / power;
}



int main(void)
{
   char *str = "0.99";
   
   double d = atof(str) ;

   printf("%f", d);

   return 0;
}

Result


Related Tutorials