CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to CCS Technical Support

Float to long conversion

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
stefan_d6



Joined: 17 Aug 2006
Posts: 6
Location: Varna, Bulgaria

View user's profile Send private message

Float to long conversion
PostPosted: Tue Oct 17, 2006 3:20 am     Reply with quote

I need to convert a float variable to long variable with rounding:
123.45 -> 123
123.56 -> 124

This can be done easily with CEIL() but it returns also float:
123.45 -> 123.00
123.56 -> 125.00

Can I use this to get long:
long_var=ceil(float_var);

Or

sprintf(string_var,"%g",float_var);
long_var=atol(string_var);
PCM programmer



Joined: 06 Sep 2003
Posts: 21708

View user's profile Send private message

PostPosted: Tue Oct 17, 2006 11:48 am     Reply with quote

The program below shows one way to do it.

Here is the output:
Quote:

rounded a = 123
rounded b = 124


Code:
#include <16F877.h>
#fuses XT, NOWDT, NOPROTECT, PUT, BROWNOUT, NOLVP
#use delay(clock=4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)

//=========================================
void main()
{
float a = 123.45;   // Want to round this to 123
float b = 123.56;   // Want to round this to 124

int16 round_a;
int16 round_b;

round_a = (int16)(a + 0.5);
round_b = (int16)(b + 0.5);

printf("rounded a = %ld\n\r", round_a);
printf("rounded b = %ld\n\r", round_b);

while(1);
}
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
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


Powered by phpBB © 2001, 2005 phpBB Group