Skip to main content
1 of 2
waspinator
  • 225
  • 4
  • 11

build fixed size strings from floats

This is likely a duplicate, but I couldn't find the original question. This is really basic, but just can't figure it out.

I'm trying to combine a few char arrays together. This is what I've tried so far.

float a = 12.3456;
float b = 5.4321;
bool c = true;

char a_string[4];
dtostrf(a, 4, 1, a_string);

char b_string[4];
dtostrf(b, 4, 1, b_string);

char c_string[2] = {'0', '\0'};
if (c) {
  c_string[0] = '1';
}

char output[12] = "-----------";

output[0] = a_string[0];
output[1] = a_string[1];
output[2] = a_string[2];
output[3] = a_string[3];

output[4] = ' ';

output[5] = b_string[0];
output[6] = b_string[1];
output[7] = b_string[2];
output[8] = b_string[3];

output[9] = ' ';

output[10] = c_string[0];

Serial.println(output);

Results in an empty string in seems.

If I remove the second dtostrf(), and change b_string[0] ... to a_string[0] Then I get 12.3 12.3 1. Doesn't seem to like having dtostrf() called more than once, but it seems like the function I want, since it allows me to set a fixed strint size. The output I'd be looking for is 12.3 5.4 1

another approach

String a_string = String(a, 1);
String b_string = String(b, 1);
String c_string = String(c);

String output;
String space = " ";

output.concat(a_string);
output.concat(space);
output.concat(b_string);
output.concat(space);
output.concat(c_string);

Serial.println(output);

This outputs 12.3 5.4 1. Is there a way to make the String fixed width? I'm looking for

12.3 5.4 1 instead of

12.3 5.4 1

What's the proper way of doing this?

waspinator
  • 225
  • 4
  • 11