Sprintf function in Arduino

Arduino doesn’t support printf function like C and C++. Which makes formatting string with numbers a little bit harder. But there’s a few ways to generate similar effect.

Using char buffer and sprintf

int height = 8223;
char buffer[100];
void setup() {
  Serial.begin(9600);
  sprintf(buffer, "Aconcagua is %d metres height.", height);
  Serial.println(buffer);
}
void loop() {
}

Create a char buffer and use sprintf to format text with int numbers. However, the sad thing is that this method does not support float, double and long long.


Using String with println
Another way to join the string with an integer or float number together is by adding String(“”) into your println() function. Which will make string and float number join together.

float height = 8223.05;
void setup() {
  Serial.begin(9600);
  Serial.println(String("") + "Aconcagua is " + height + " metres height.");
}
void loop() {
}

However, we still cannot control the decimal of output float number by this way.

Comments