Jump to content
43oh

How to convert String to Float


Recommended Posts

Hi, I'm using a launchpad and I want to convert a string value (weight) to a float or double value, have tried atof, but it doens't work. Do you know a way to achive this cast?

 

I have also tried float() or double(), like this:

 

String str="002.845";

float weight= float(str);

 

or

 

char str[7]="002.845";

double weight= atof(str);

Link to post
Share on other sites

Hello @@Govs

 

You don't say in your post which LaunchPad you are using.  It is not documented on the Energia site but the toFloat() function works in Energia with the String class on at least some LaunchPads.

// Energia example using the toFloat() function with the String class
// Tested on MSP430F5529 and MSP430G2553 

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  String pi;
  pi = "3.14153";
  double X = pi.toFloat();
  Serial.print("Pi = ");
  Serial.println(X, 5);
  
  while(1) {}
}

EDIT:  I should add that there was a really good series of posts on 43oh recently here on how the String class can get you in trouble on a microcontroller....

Link to post
Share on other sites

And yet another way if you are reading from the serial monitor in Energia is to use parseInt() and parseFloat() something like the following:

// Demostrates the use of Serial.parseInt and Serial.parseFloat in Energia
// Tested on MSP430F5529

void setup()
{
  Serial.begin(9600);
}

void loop()
{  
  Serial.println("Enter an integer... ");
  while(Serial.available() == 0) {
  }
  int a = Serial.parseInt();
  Serial.print("You entered: ");
  Serial.println(a); 
  
  Serial.println("Enter a floating point number... ");
  while(Serial.available() == 0) {
  }
  float b = Serial.parseFloat();
  Serial.print("You entered: ");
  Serial.println(;
}
Link to post
Share on other sites

If you don't need a routine that supports a lot of different formats and need to have extensive error handling then it should be fairly easy to implement one.

 

This is what I did for integers:

int parseInt (char *s) {

	int c, res = 0, negative = 0;

	if(*s == '-') {
		negative = 1;
		s++;
	} else if(*s == '+')
		s++;

	while((c = *s++) != '\0') {
		if(c >= 48 && c <= 57)
			res = (res * 10) + c - 48;
	}

	return negative ? -res : res;

}

For decimals it is just finding the position of the decimal point and do a divison of the integer result?

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...