Here is example code for using sprintf() to print formatted integers and dtostrf() for floats that works:
(not very elegant, but then neither is C, esp for printing.)
/* Print padded (aligned) integers and floats from Arduino environment
* sprintf() for integers www.cplusplus.com/reference/cstdio/printf/
* and dtostrf() for floats dtostrf(FLOAT,WIDTH,PRECSISION,BUFFER); gist.github.com/2343665 www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#g6c140bdd3b9bd740a1490137317caa44
*/
int n;
int m;
byte i = 1;
float x;
char c[10]; // long enough to hold complete integer string
char f[10]; // long enough to hold complete floating string
void setup() {
randomSeed(1);
Serial.begin(57600);
}
void loop() {
n = random(-1000,1000); // generate a random integer
x = n/1000.0; // convert to a float <= |1.0|
m = sprintf(c, " %3d: %5d ", i,n); // build integer string using C integer formatters (m is length, and not used in this code)
Serial.print(c);
dtostrf(x,6,3,f); // -n.nnn Use this for a consistent float format
Serial.println(f);
i++;
delay(1000);
}
Output:
1: -193 -0.193
2: 249 0.249
3: -927 -0.927
4: 658 0.658
5: -70 -0.070
6: 272 0.272
7: 544 0.544
8: -122 -0.122
9: 923 0.923
10: 709 0.709
11: -560 -0.560
12: -835 -0.835