Go Down

Topic: Zero Padding or Leading Zeros (Read 3 times) previous topic - next topic


I totally undestand.  Thanks for the breakdown jraskell.  I'm going to try sprintf out when I get home.


and I think it's always useful to know that the variety of C library functions in those modules are available for your usage within Arduino sketches by default.

Could be useful to have a list of functions avalible that don't require an include directive?



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.)

Code: [Select]
/* 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() {     

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)

  dtostrf(x,6,3,f);                          // -n.nnn Use this for a consistent float format

   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


Could be useful to have a list of functions avalible that don't require an include directive?

That might be a moving target - I don't suppose the Arduino development team consider that the set of implicitly-included headers for any given library or for the environment as a whole is parts of the defined interface for that library or environment. (Microsoft don't either; they're always changing things around and breaking code that took the implicit includes for granted.)
I only provide help via the forum - please do not contact me for private consultancy.

Go Up