How do I convert a float into char*?

Asked this question on Electrical Engineering Stack Exchange and was directed here:

Pretty self explanatory; how would I go about converting a float into a char*? I have code in which the float 'resistance' is constantly being updated. I would like to be able to update the variable 'result' to take the value of 'resistance'. Here is some of the code, in case it helps:

``````const char * result = "";
float resistance = 2.5;

result = resistance; //This bit (obviously) doesn't work
``````

Thanks for your help!

There is a function in the standard Arduino library called `dtostrf()`. I think of it as "Decimal to String Float". You pass in the float, how wide you want the whole number to be (if it will fit), the number of decimals of precision - and the buffer you want it to fill.

Note that! You need to provide the buffer, and you need to be careful to provide more than enough! Don't forget to add 1, too (to store the NUL character at the end):

``````char result[8]; // Buffer big enough for 7-character float
dtostrf(resistance, 6, 2, result); // Leave room for too large numbers!
``````

This will give `result` values like `" 1.23"` and `" -1.23"` and `"123456789"` (without the quotes). Note the last example - it won't truncate the number if it's too large, and that 10- character `result` (don't forget the final `NUL`) just overflowed your buffer...

Incidentally, if you specify a negative width, it won't right-justify the answer, it'll left-justify it (put any spaces on the end instead of the beginning).

• Did the trick nicely! Thank you very much kind sir :) Aug 1, 2016 at 14:12

Basically you are trying to convert a 4-byte variable (float) to a 4-byte string (char variables are 1-byte sized). More info about Arduino data types here http://playground.arduino.cc/Code/DatatypePractices

You can try the answers to these questions https://stackoverflow.com/questions/18270974/how-to-convert-a-float-to-a-4-byte-char-in-c

https://stackoverflow.com/questions/24420246/c-function-to-convert-float-to-byte-array

I admit that I am confused by the use of `const char * result = "";` in your example.

The "const" keyword makes the variable as "read-only" and therefore you can't modify it. https://www.arduino.cc/en/Reference/Const

Edit: Unfortunately I don't have an Arduino device right now to test myself the above solutions

• The `const` keyword does not make the variable read-only. The variable here is a pointer, and it need not be constant. The `const` keyword qualifies the data being pointed to, not the pointer itself. In other words, you are not allowed to modify the string through that pointer. If you want a constant pointer, declare it as `char * const result` (or `const char * const result` if you want a `const` pointer to `const` data). Jul 29, 2016 at 20:14