# Rounding sensor values to 2 decimal places

I’m reading sensor values from a DHT11 sensor for Temperature and Humidity. Everything works as expected but I’m having trouble rounding the values to 2 places. I used the round function for the sensed values before sending it to the lcd.print function but I can’t get it to work. Any suggestions? Code snippet is below…

``````// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a
// very slow sensor)
float h = dht.getHumidity();

float t = dht.getTempCelcius();
float f = dht.getTempFarenheit();

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.getHeatIndex();
float dp = dht.getDewPoint();
float k = dht.getTempKelvin();

**f = round(f*10)/10; //set precision to 1 decimal**
**h = round(h*10)/10; //set precision to 1 decimal**
Serial.print("Humidity: ");
Serial.print(h);
lcd.setCursor(0, 0);
lcd.print("Humidity " + String(h) + "%");
lcd.setCursor(0, 1);
lcd.print("Temp " + (String(f) + (char(223)) + "F")); //char 223 is the Degree symbol
``````

There is a difference between rounding the raw value and converting a float value to string.
Floating point datatypes cannot be rounded perfectly to any arbitrary value and/or precision due to the way how these values are stored in binary form.

Since we always recommond to stay away from `String` objects the widely preferred way to do what you want could look like this

``````  char str[32]
snprintf(str, sizeof(str), "Humidity %.2f%%", h);
lcd.print(str);
snprintf(str, sizeof(str), "Temp %.2f%cF", f, 223);
lcd.print(str);
``````
2 Likes

Thank you. That worked perfectly!

1 Like

A follow up question, I’m trying to get the LCD messages to blink and this might be a really “hack” way to do it and I thought the following code would work but I’m getting a “invalid use of non-static member function” error on the lcd.clear function. Thoughts?

``````if (f >= 75)
{
lcd.clear;
lcd.setCursor(0, 1);
lcd.print("Temp Excursion!!!!!!");
delay(500);
lcd.clear;
lcd.print("Temp Excursion!!!!!!");
delay(500);
lcd.clear;
lcd.print("Temp Excursion!!!!!!");
delay(500);
lcd.clear;
}

if (h >= 90)
{
lcd.clear;
lcd.setCursor(0, 2);
lcd.print("Humid Excursion!!!!!!");
delay(500);
lcd.clear;
lcd.print("Humid Excursion!!!!!!");
delay(500);
lcd.clear;
lcd.print("Humid Excursion!!!!!!");
delay(500);
lcd.clear;
}``````

I’m an idiot. I forgot the () after lcd.clear. It should be lcd.clear();

It now works but I’m surprised there’s no function for lcd.blink ?