stefan_d6
Joined: 17 Aug 2006 Posts: 6 Location: Varna, Bulgaria
|
Float to long conversion |
Posted: Tue Oct 17, 2006 3:20 am |
|
|
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
|
|
Posted: Tue Oct 17, 2006 11:48 am |
|
|
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);
} |
|
|