View previous topic :: View next topic |
Author |
Message |
GiG
Joined: 03 Sep 2021 Posts: 39
|
round function in CCS |
Posted: Fri Sep 24, 2021 11:07 pm |
|
|
Hi
I had a question about rounding a number that is thrown into an integer
I read the temperature and I want it to be displayed in a rounded way on the screen to prevent the temperature from jumping when changing at the edges.
I tried several functions but they did not work. wanted to find a solution
Or function
for example :
27.51 to equal 28
27.49 to equal 27
i'm using integers do i need to use floats instead ?
thank you
ccs ide |
|
![](templates/subSilver/images/spacer.gif) |
Ttelmah
Joined: 11 Mar 2010 Posts: 19358
|
|
Posted: Sat Sep 25, 2021 12:25 am |
|
|
You say you are using integers, but 27.49 is a float.
Search on 'scaled integers'. You never want to use float unless you must.
However assuming this temperature is being read from something (ADC
or some form of external sensor etc.), if you can convert the incoming
value to a temperature in (say) 1/100ths of a degree, then you can scale
this result to give integer degrees in a sensible 'rounded' way.
So if you have the values as (say 2751 and 2749, simply:
(val+49)/100
Would give 28 for 2751 and 27 for 2749. |
|
![](templates/subSilver/images/spacer.gif) |
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sat Sep 25, 2021 1:09 am |
|
|
For rounding floating point numbers, see this CCS FAQ article:
http://c-faq.com/fp/round.html
Example:
The program below displays these results in the MPLAB v8.92 simulator
output window:
Test program:
Code: | #include <18F46K22.h>
#fuses NOWDT
#use delay(internal=4M)
#use rs232(UART1, baud=9600, ERRORS)
// 27.51 to equal 28
// 27.49 to equal 27
#define round(x) (signed int)(x < 0 ? (x - 0.5) : (x + 0.5))
//=================================
void main()
{
float input;
signed int result;
input = 27.51;
result = round(input);
printf("%d \r", result);
input = 27.49;
result = round(input);
printf("%d \r", result);
input = -27.51;
result = round(input);
printf("%d \r", result);
input = -27.49;
result = round(input);
printf("%d \r", result);
while(TRUE);
} |
|
|
![](templates/subSilver/images/spacer.gif) |
|