robtillaart:
The code works for numbers within the rang 0..999
try the code with a number that is longer or a negative and you see some point to improve the function.
Quite right. I had meant to point that out in my reply.
In practice I would probably not use such a function in my code as it only replaces two lines with one in the main code and I would feel more in control of the formatting by having the sprintf on the line before the print instead of hidden in a function. It would also become more and more difficult to extend the function to handle other formats properly.
@UKHeliBob
It was more meant as an exercise for the OP, not as a remark on your code sec.
I've seen enough of your code to know you would implement it as you said
This one works but only for "3 zeros"
char* formata_zeros_esquerda(int foo, String total_casas)
{
char buffer_formata_zeros_esquerda[4];
sprintf(buffer_formata_zeros_esquerda,"%03d", foo);
return buffer_formata_zeros_esquerda;
}
NOTE that numberBuffer is a global variable and not local to the formatBuffer function
Then, there's really no reason for the function to return a pointer to it, is there? And, the function is not called formatBuffer. It's called formatForPrint().
Picky, picky (:)) but correct, of course in respect of the global variable.
I was focussing on not committing the sin of returning a pointer to a variable that was local to the function and missed the blindingly obvious.
NOTE that numberBuffer is a global variable and not local to the formatBuffer function
Then, there's really no reason for the function to return a pointer to it, is there? And, the function is not called formatBuffer. It's called formatForPrint().
The functions like char* itoa() does have the buffer as parameter AND return value. The added value of giving this pointer as return value is that the function itself can be used as function parameter or in other expressions e.g.
Serial.println(itoa(....));