int foo;
char buffer[4];
void setup() {
Serial.begin(19200);
foo = 5;
sprintf(buffer,"%03d", foo);
Serial.println(buffer);
}
void loop() {
// put your main code here, to run repeatedly:
}
The second parameter is a format string. %d is decimal, %03d is decimal with three leading zeros.
I don't know if Serial.print provides any settings for that.
Could always force it I suppose:
// time to print a number
Serial.println ("printing a 3 digit number ");
if (numberToPrint <=9){
Serial.print("00");
Serial.println(numberToPrint);
}
if ((numberToPrint>=10) && (numberToPrint <=99)){
Serial.print("0");
Serial.println(numberToPrint);
}
if (numberToPrint>99){
Serial.println(numberToPrint);
}
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;
}