how do I convert a float to a char *?

10 Jun 2013

Hello all. The MCP9700 Linear Temperature Sensor library creates a float value. I would like to convert the float value to a char * value. Then send the char * value using the wifly websocket example ws.send(char * value). How do I convert the float value to a char * value? Thank you for the help in advance.

10 Jun 2013

After searching Google I arrived to a very simple solution. My solution:

Tav  = sensor.GetAverageTemp(); // Calculate average temperature from N samples

char cVal[8];  
char* Tav_str;

sprintf(cVal,"%.2f", Tav);

pc.printf("Temp Average is: %s\r", cVal);

The above code section seemed to work as expected. Is there another way to achieve a solution to my question stated above?

10 Jun 2013

What your code does is effectively write a string (char array) with the float value. The advantage is that it is independent of type of float, but it does cost you in more data and losing accuracy (which won't be that important with a temperature).

So if you just want to send it as a human readable string, then this is the solution you need (where you need to watch out your temperature can't become too high/low, so it doesn't fit in your 7+1 characters anymore). If you want to send the raw float data there is another method, but I think this should work fine for your requirements.