Round float in sprintf

Description

I display sensor data in a lvgl labels with an ESP32 and ILI9341 display, the sensor data it’s a float type and I formated to char with sprintf for set the text labels but at the formated moment, one of the float type has lot of decimals, andonly I need two decimals, how can I round the float for formated to char? Thanks for all.

What MCU/Processor/Board and compiler are you using?

ESP32 with Arduino IDE

What LVGL version are you using?

v.7.7.2

What do you want to achieve?

Display the data sensor with only two decimals

What have you tried so far?

Round the float type with float temp = round(airSensor.getTemperature()); but when I formated to char, the char have only equal to zero the two first decimals and have the next decimals equal

Code to reproduce


    int co2 = airSensor.getCO2();
    float temp = airSensor.getTemperature();
    float hum = airSensor.getHumidity();

     char co2C[5];
     char tempC[5];
     char humC[5];
     
      sprintf(co2C, "%i", co2);
       sprintf(tempC, "%f", temp);
        sprintf(humC, "%f", hum);

     Serial.println(co2C);
     Serial.println(co2);
     Serial.println(tempC);
     Serial.println(temp);
     Serial.println(humC);
     Serial.println(hum);
     
    lv_label_set_text(label_co2, co2C );
    lv_label_set_text(label_temp,  tempC);
    lv_label_set_text(label_hum,  humC );

Screenshot and/or video

Print data

Display

Thanks!

Hi,
this is not problem with LVGL, but Arduino core formatting instead (if it is really a problem). If you don’t want decimal places in the result, use proper %f formatter for example %.2f (see http://www.cplusplus.com/reference/cstdio/printf/ for explanation).
EDIT: maybe your tempC[] array is too small :wink: … (you need space for null terminator)

1 Like

Buffers are too small:

char co2C[5];
char tempC[5];
char humC[5];

You need:

char co2C[6];
char tempC[6];
char humC[6];

To have at least

  • 2 digits
  • 1 decimal point
  • 2 decimal digits
  • 1 null character to indicates end of string

You can also tell how many decimal digits you wants with sprintf format string:

char buffer[6];
sprintf(buffer, "%.2f", 12.3456789); // Buffer will get "12.34";
1 Like