-->
Page 1 of 1

Round float problem

PostPosted: Mon May 22, 2017 5:53 am
by Hydro
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

Re: Round float problem

PostPosted: Tue May 23, 2017 5:56 am
by btidey
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

Re: Round float problem

PostPosted: Tue May 23, 2017 6:37 am
by Hydro
It's not possible to hold the float into variable without use int ?

Re: Round float problem

PostPosted: Wed May 24, 2017 3:50 am
by btidey
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.