CCS does not monitor this forum on a regular basis. Please do not post bug Reports on this forum. Send them to support@ccsinfo.com
Author Message
GiG

Joined: 03 Sep 2021
Posts: 28

 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
Ttelmah

Joined: 11 Mar 2010
Posts: 17485

 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.
PCM programmer

Joined: 06 Sep 2003
Posts: 21508

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:
 Quote: 28 27 -28 -27

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); }
 Display posts from previous: All Posts1 Day7 Days2 Weeks1 Month3 Months6 Months1 Year Oldest FirstNewest First
 All times are GMT - 6 Hours Page 1 of 1

 Jump to: Select a forum Software----------------General CCS C DiscussionCode LibraryEZ App LynxBest OfKnown Issues Hardware----------------CCS ICD / Mach X / Load-n-Go
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum