snprintf() with variable with

C0d3man

Well-known member
snprintf() with variable width

Hi all,

I tried to write a wrapper for snprintf():

Code:
#include <Arduino.h>
#define LCD_cols 16

void display_float(float var, uint8_t size_number, uint8_t size_fraction, bool zeros, bool brackets, bool sign) {
  char s[LCD_cols + 1];

  if (size_fraction > 0) {
    if (zeros == true && sign == true)
      snprintf(s, sizeof(s), "%+0*.*f", size_number + size_fraction + 2, size_fraction, var);
    else if (zeros == true && sign == false)
      snprintf(s, sizeof(s), "%0*.*f", size_number + size_fraction + 1, size_fraction, var);
    else if (zeros == false && sign == true)
      snprintf(s, sizeof(s), "%+*.*f", size_number + size_fraction + 2, size_fraction, var);
    else if (zeros == false && sign == false)
      snprintf(s, sizeof(s), "%*.*f", size_number + size_fraction + 1, size_fraction, var);
  } else {
    if (zeros == true && sign == true)
      snprintf(s, sizeof(s), "%+0*d", size_number + 1, int(var));
    else if (zeros == true && sign == false)
      snprintf(s, sizeof(s), "%0*d", size_number, int(var));
    else if (zeros == false && sign == true)
      snprintf(s, sizeof(s), "%+*d", size_number + 1, int(var));
    else if (zeros == false && sign == false)
      snprintf(s, sizeof(s), "%*d", size_number, int(var));
  }

  if (brackets == true) {
    char tmp[LCD_cols + 1];

    strcpy(tmp, s);
    snprintf(s, sizeof(s), "[%s]", tmp);
  }

  Serial.print("var="); Serial.println(var);
  Serial.print("s="); Serial.println(s);
}

void setup() {
  Serial.begin(9600);
  Serial.println("START");
  display_float(-0.75f, 2, 1, false, false, false);
  Serial.println("READY");
}

void loop() {
  while(42==42);
}

My problem: it seems that snprintf() does not support the "*" for setting the width. Anyone an idea what I am doing something wrong or if snprintf() does not support this?
 
Last edited:
My problem: it seems that snprintf() does not support the "*" for setting the width. Anyone an idea what I am doing something wrong or if snprintf() does not support this?

When I run your program on T4.1 with Arduino 1.8.19 and TD 1.57, I get the output shown below, which seems right, i.e. 1 digit to the right of the decimal. Is this what you get? What do you want the output to be? If you want the outputs to be the same in this case, the second size argument should be 2.

Code:
START
var=-0.75
s=-0.8
READY
 
Hi @joepasquariello,

Many thanks for testing. Sorry - I totally forgot to show my output. I got:
Code:
START
var=-0.75
s=
READY

But by your successful test I found the solution to the problem: I had activated the option "Smallest code". With "Faster" it works:

Code:
START
var=-0.75
s=-0.8
READY

So, thanks again for testing!

Regards, Holger
 
Back
Top