9 years, 8 months ago.

How to convert String to Float value

I want to send a string over serial to my mBed. Once i receive this string or array of characters, how can I convert the numbers given to a float value?

I have an array of char[9] = {1,2,3,4,5,.,4,3,2} or a string "12345.432", how do I convert this to a float = 12345.432??

Thank you for all the help

2 Answers

9 years, 8 months ago.

Use the function atof() which is part of stdlib.h (or cstdlib).

You can use it like that

Using atof

#include <cstdlib>

void main()
{
  float cnv;

  cnv = atof("3.1415");

  while(1)
  {
  }
}

Accepted Answer
9 years, 8 months ago.

Hi, You can use a scanf function or do the maths iterating over the char array. For this conversion you should probably use double instead of float (however give it a try with floats you should quickly see the issue).

	double iPart = 0.0, dPart = 0.0, f = 0.0, mult = 0.1;
	const char *buff  = "12345.432";
	
	sscanf(buff,"%f",&f);
	printf("%f\n",f);
	
	f= 0.0;
	char *p = (char*) buff;
	while(*p != '.') {
		 iPart = iPart*10 + ((*(p++)-'0')); 
	}
	p++;
	while(*p!= '\0') {
		 dPart += ((*(p++)-'0'))*mult;
		 mult *= 0.1;
	}
	f = iPart + dPart;
	printf("%f\n",f);

The scanf is big function able to handle lost of conversion etc etc.. for a simple conversion and with low memory using the second option is probably the best. Hope this helps Have a nice day. Clément