• C

How do i convert a string into a float ?

Hi
  In my code ,i need to give an input value as a comand line parameter ie,a string value..
 i need to convert that string into a float value for my calculation...i need a help in this issue..

Thanks in Advance..
sathish
sathishrdhAsked:
Who is Participating?
 
Todd GerbertIT ConsultantCommented:
0
 
point_pleasantCommented:
try atof or strtod
0
 
ssnkumarCommented:
Sample code to show the usage of strtod:
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  char number[] = "3.141592";
  double pi = 0.0;
  pi = strtod(number, NULL);
  printf("pi = %lf\n", pi);
  return 0;
}
0
Turn Raw Data into a Real Career

There’s a growing demand for qualified analysts who can make sense of Big Data. With an MS in Data Analytics, you can become the data mining, management, mapping, and munging expert that today’s leading corporations desperately need.

 
point_pleasantCommented:
see below for the code and explanation of ssnkumar's comment

http://www.codecogs.com/reference/c/stdlib.h/strtod.php
0
 
ssnkumarCommented:
Also, you can look at this page, for the explanation of strtof():
http://www.java2s.com/Tutorial/C/0420__stdlib.h/strtof.htm
0
 
Todd GerbertIT ConsultantCommented:
The beauty of sscanf, though, is that it doesn't necessarily require that the string with the float value contain only the float value:

#include <stdio.h>

int main(int argc, char *argv[])
{
	char cmdLineArg[] = "/FloatVal=2.3";
	float f;

	int parsed = sscanf(cmdLineArg, "/FloatVal=%f", &f);

	if (parsed)
		printf("The value provided with the FloatVal argument is: %f\n", f);
	else
		printf("Could not parse a float value from the provided string.\n");

	printf("Press ENTER to exit.");
	scanf("%*c");
}

Open in new window

0
 
ssnkumarCommented:
ModCorlEEone,

Thanks for the advice. I will keep that in mind and do as suggested.

Regards,
Narendra
0
 
eagerCommented:
Command line arguments are passed in argv, starting with index 1.  Assuming that the value is the first on the command line, after the program name, try the following:

#include <stdlib.h>
int main (int argc, char *argv[])
{
   double val;
   char *endp;
   /* include checking number of args. */
   val = strtod (argv[1], &endp);
   if (endp == argv[1] || *endp != '\0')
   {
       /* Handle error */
   }


0
 
evilrixSenior Software Engineer (Avast)Commented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.