0

I have made a temperature sensor function that returns a float number with 6 digit after the . (eg: 28.500000)

Using:

float fTemp;
...
printf("Temp =  %.1f", fTemp);

I can limit the temperature decimal to one, and everything is fine. (eg; 28.5)

Now I would like to pass the tempere to my Xively account and I have this function:

extern xi_datapoint_t* xi_set_value_f32( xi_datapoint_t* dp, float v );

How can I convert temperature value float to one decimal and pass it to the xi_set_value_f32?

Thank you, dk

d82k
  • 379
  • 7
  • 17
  • Due to the nature of floating point number that's impossible to do, and not only that, it's entirely pointless. – fvu Jul 28 '13 at 12:06
  • Impossible because floating pointers are not exact (meaning that for certain values a division may end off very close to the expected result but not spot on - eg 16.0 / 10.0 may give 1.5999999 as a result) and pointless as it's a **display concern** that should be solved at display time, not at storage time. – fvu Jul 28 '13 at 12:22

2 Answers2

2

Do this

int tempNumber;

tempNumber = fTemp*10;

Now do this 

fTemp = (float)(tempNumber/10.0);

What I have done here is multiplied your floating number to 10 and save in an integer, this way I have preserved first decimal number of your floating point into an integer and therefore all values after point are neglected.

Next what I did is to divide your temporary integer by 10.0 typecast the result and save back in the fTemp variable

Sanyam Goel
  • 2,138
  • 22
  • 40
  • 1
    You may want to use `round` to round to nearest. – ouah Jul 28 '13 at 12:10
  • @ouah yes that is even better really :) – Sanyam Goel Jul 28 '13 at 12:12
  • 2
    Will often work as intended but not always due to how fp works, please read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – fvu Jul 28 '13 at 12:24
1

Standard C function round/roundf in math.h should do it.

#include <math.h>    

// ...

fTemp = roundf( fTemp * 10.0f ) / 10.0f;

Again, why would you like to do this? Sounds better to keep the precision and just round it when it is outputed.

FreLo
  • 11
  • 4
  • Thank you for your answer. Actually I'm not able on xively to display only 1 decimal, it seems it is not in the options. – d82k Jul 28 '13 at 13:06