What is the best way to "print" (Serial.print) an integer with a specified minimum number of digits (ex. printf("%03d", 1) -> 001)?
What is the best way to "print" (Serial.print) an integer with a specified minimum number of digits (ex. printf("%03d", 1) -> 001)?
Use sprintf() to print to a buffer, then Serial.print() the buffer. It's really the only way. That makes it the best way automatically.
if it's less than 1000, print a zero if it's less than 100, print a zero if it's less than 10, print a zero print the number
but that's better done in a loop that starts with 1000 and divides by 10 until less than 10.
I've worked it to make fixed-point integers print fast.
PaulS: Use sprintf() to print to a buffer, then Serial.print() the buffer. It's really the only way. That makes it the best way automatically.
I thought about that but I didn't thing that would be the preferred way because printf and friends (sprintf, fprintf, vsprintf, etc...) tend to use a lot of program (FLASH) space.
but that’s better done in a loop that starts with 1000 and divides by 10 until less than 10.
I would disagree here. The loop approach is harder to implement and will consume a lot more memory because the Arduino lacks hardware division. The approach with the if statements is much simpler and compiles to less instructions.
Even in case of variable digits I would stick with the if statements like so:
switch (digits) {
case 5: { if (n<10000) { print('0'); }}
case 4: { if (n<1000) { print('0'); }}
case 3: { if (n<100) { print('0'); }}
case 2: { if (n<10) { print('0'); }}
}
print(n);