How to safely and reasonably convert a float or double to string or char array?

@krupski

I have tried your trick by renaming the files and it did not work. I think it was simple enough for me not to make a mistake but again I could be wrong. (I am using latest Arduino).

However since I did a small test, I decided to share the result (not sure if it is meaningful but again it is a job done)

For Dtostrf:

#include "MemoryFree.h"

void setup() 
{
 int availableMemory;
 availableMemory = freeMemory();

 Serial.begin(115200);
 uint8_t buffer[60] = {};
 float inputNumber = 1357.125;
 uint32_t start, end;
 
 Serial.println(availableMemory);
 
 start = micros();
 dtostrf(inputNumber, 0, 3, buffer);
 end = micros();
 
 Serial.println(end - start);

 Serial.write(buffer, 60);
 
}
// the loop function runs over and over again forever
void loop() 
{

 
}

Result:

Using dtostrf:
Flash space = 3790
Global variable = 190
Free memory at the beginning = 7937
Micros taken = 120
Output is: 1357.125 [00] X 52

for sprintf:

#include "MemoryFree.h"

void setup() 
{
 int availableMemory;
 availableMemory = freeMemory();

 Serial.begin(115200);
 uint8_t buffer[60] = {};
 float inputNumber = 1357.125;
 uint32_t start, end;
 
 Serial.println(availableMemory);
 
 start = micros();
 sprintf (buffer, "%7.3f\r", inputNumber);
 end = micros();
 
 Serial.println(end - start);

 Serial.write(buffer, 60);
 
}

// the loop function runs over and over again forever
void loop() 
{

 
}

results:

Without modifying the IDE:
Flash space = 3766
Global variable = 196
Free memory at the beginning = 7931
Micros taken = 80
Output is: [20] [20] [20] [20] [20] [20][3F = ‘?’][0D = ‘\n’] [00] X 52

With modifying the IDE:
Flash space = 3766
Global variable = 196
Free memory at the beginning = 7931
Micros taken = 80
Output is: [20] [20] [20] [20] [20] [20][3F = ‘?’][0D = ‘\n’] [00] X 52

@westfw
I am not sure about (avr-libc documentation) but the the other stostrf I found they let you set the number of digits after the sign. This technically solve all the problems. I am not sure what they do if they cannot fit it in the given number of digits but they definitely have a way to know.

__ftoa_engine() precision is different from in current arduino dtostrf. the precision tells the maximum number of digit coming out. that is why they put a 7 there to indicate the want only 7 numbers to be printed in a 9 byte buffer. Not sure about the return though. The implementation is odd with zero comments which make it tougher.