Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By Hydro
#66179 Hi

I have a dht22 connect to my esp8266 and I read the temperature and the humidity to float variables.

These float have a lot of decimal, if I print them I've got something like :

23.45634953

I want this float on another variable with only two decimal, that's way I can send this variable to my home automation system.

I try to round it with :

round(float*100)/100

But it doesn't work, the variable have all decimal, it's like I didn't do something :(

I try to convert it to int then convert it back to float, but it doesn't work.

I try to convert it to char[2] then convert it back to float, it doesn't work either.

Is there a way to save the float value to another variable with only two decimal ?

Thank a lot
User avatar
By btidey
#66213 There is no such thing as a standard variable with 2 decimal places. If you are trying to print a float with 2 decimal places then use printf with a specifier like %.2f as in
Serial.printf("Value is %.2f", value);

If you want to hold the result in a numeric variable then maybe consider using an int with value multiplied by 100
User avatar
By btidey
#66243 You can obviously store a value in a float variable, but that doesn't control in any way the number of decimal digits. That's because a float is a binary representation of a number https://www.arduino.cc/en/reference/float

Because it is a binary representation, values when calculated that you think are a simple short decimal get represented as the nearest equivalent which when printed back as a decimal may contain lots more decimal places.

Normally you only care about the number of decimals when you print of convert to a string. That is why the %f in a printf has full features to control how the number is represented.