rounding off to first decimal

Thread Starter

ak52

Joined Oct 15, 2014
230
Hello everyone,

I am looking to round my float value to a single digit after decimal,not just to display,but to use in mathematical calculations.
Here is what i have so far:
Code:
float value = 5.65893    //example float
int temp = 0;

temp = value*10;
value = temp/10.00;

//value is 5.6
The above code works,but i need to use an extra variable temp for typecasting purpose.
Is there a work around this??

Thanks,
AK
 

WBahn

Joined Mar 31, 2012
29,979
Hello everyone,

I am looking to round my float value to a single digit after decimal,not just to display,but to use in mathematical calculations.
Here is what i have so far:
Code:
float value = 5.65893    //example float
int temp = 0;

temp = value*10;
value = temp/10.00;

//value is 5.6
The above code works,but i need to use an extra variable temp for typecasting purpose.
Is there a work around this??

Thanks,
AK
But is 5.6 the answer you want if you are rounding 5.65893 to the nearest tenth?

If you don't want to use a library routine, how about the following:

value = ((int) (10*value+0.5))/10.0;
 

Thread Starter

ak52

Joined Oct 15, 2014
230
How about:

value = round(value*10)/10;
I am using XC16 compiler, inst round used for integer values only?,Anyways i tried using round and roundf,both gave me error(i included math.h also).
But is 5.6 the answer you want if you are rounding 5.65893 to the nearest tenth?

If you don't want to use a library routine, how about the following:

value = ((int) (10*value+0.5))/10.0;
Round may not be the correct word here,sorry for that,i just need the first digit after the decimal point and ignore the rest for my calculations.
 

WBahn

Joined Mar 31, 2012
29,979
I am using XC16 compiler, inst round used for integer values only?,Anyways i tried using round and roundf,both gave me error(i included math.h also).

Round may not be the correct word here,sorry for that,i just need the first digit after the decimal point and ignore the rest for my calculations.
Then remove the 0.5 from the expression.

The term you are looking for is "truncate" instead of round.

How do you need to handle negative values? For instance, what result would you want for -5.67?
 

Thread Starter

ak52

Joined Oct 15, 2014
230
I got it.Thanks for your help WBahn.
Negative values is not a problem ,because i make sure that the values are always positive.

AK
 
Top