Reputation: 49
I want to convert, for example, the number 12 to 0012. So that the number is always 4 characters long. I tried it with this code:
int number;
int result;
void setup() {
number = 12;
Serial.begin(9600);
result = printf("%03d", number);
}
void loop() {
Serial.println(result);
}
However this code outputs only -1 instead of 0012. What is wrong with this code?
Upvotes: 4
Views: 17806
Reputation: 76607
Integers cannot and do not recognize formatting like leading zeros.
The only way to store this type of information would be to use a string (like a char[]
instead of an integer, however it looks like you are simply writing out the value so you shouldn't need a variable for it (as printf()
will handle that for you).
// %04d% will pad your number to 4 digits
printf("%04d", number);
If you do actually need to store your value, you can use sprintf()
and declare your result
as seen below :
int number;
char *result = malloc(5);
and then set it within your setup()
function as such :
sprintf(result, "%04d", number);
Using both of these changes, your updated code might look like :
int number;
char *result = malloc(5);
void setup() {
number = 12;
Serial.begin(9600);
sprintf(result, "%04d", number);
}
void loop() {
Serial.println(result);
}
Consider formatting your values when you are outputting them, otherwise you can use the integer values to perform any arithmetic and calculations with.
Upvotes: 9
Reputation: 41
What's wrong with the code is that you are printing the return value of the 'printf' call. It returns the number of characters printed. Since it looks like stdio hasn't been setup yet, it returns -1 as an error flag. Read the manual page again, carefully.
On this line:
result = printf("%03d", number);
we want to use 'sprintf' and not 'printf'.
'sprintf' needs to put its output string somewhere. Maybe pre-allocate it, making sure it is larger than your longest output string plus one (to hold the terminating nul character). Do not allocate it inside of 'setup', but put it outside of any routine (since you initialize it in one routine, and use it in another).
char buf[6];
r = sprintf(buf, "%04d", number);
// now print the string inside of 'buf'
Serial.println(buf);
Upvotes: 4