3

My arduino is meisuring the tempature and gives values like: 28.58 Degrees Celcius. I would like to round this up to one decimal. I could make the variable one shorter by cutting the "8" off which would desplay 28.5. Yet this feels a bit like cheating as it mathimatical not correct. Does anyone know how to round up/down. Which would show my tempature as 28.6.

Extra advice needed. I am sending the tempature by Serial to my RPi which has a python code running. Would you suggest doing the rounding in the Arduino code or in The Python code.

Thanks in Advance!

Anton van der Wel
  • 215
  • 1
  • 2
  • 16

2 Answers2

4

You can round in C by multiplying for the significance, adding +0.5, round down (equals as casting to an integer) and divide.

float f_rounded = ((int) (f * 10.0 + 0.5) / 10.0);

28.6 will be:

float f_rounded = ((int) (28.6 * 10.0 + 0.5) / 10.0) 
                = ((int) 286.5) / 10.0 = 286 / 10.0 = 28.6

In Python it is equal (except the cast operator is int(...)

Update: for negative numbers +0.5 should be -0.5

Credits for Edgar Bonet: using round works for both positive and negative numbers:

float f_rounded = round(f * 10) / 10.0;
Michel Keijzers
  • 13,014
  • 7
  • 41
  • 58
4

As far as I know, the Serial.print (or println) does rounding up and down. All you have to do is take a float variable and do Serial.print( value, 1);

Without extra parameter, the default is choosen, which is 2 decimal digits: Serial.print( value, 2);

Why do you want to shorten the bytes over the Serial ? You can just as well send two decimal digits and process the value in Python.

Jot
  • 3,276
  • 1
  • 14
  • 21