|
-
October 30th, 2002, 03:27 AM
#1
Seperating Integer & Fractional Part
Helo,
I have a double value ,say 1.4.
double val = 1.4;
I want to seperate the Integer & Fractional Part. "1" & "4" from that val like
int val1 =1
int val2 = 4(without the ".")
How Can I do that.
Thanks...
-
October 30th, 2002, 04:41 AM
#2
Code:
void main()
{
float a=5.8;
int i,j;
i=a;
j= (a -i) *10;
printf("%d %d", i,j);
}
but it will work only if your fractional part length is 1.
Otherwise you won't get the extract fractional portion by this code
-
October 30th, 2002, 04:52 AM
#3
Try:
Code:
double d, ip;
d = 1.4
int fp = 10 * modf( d, &ip );
Regards,
ZDF
What is good is twice as good if it's simple.
"Make it simple" is a complex task.
-
October 30th, 2002, 05:09 AM
#4
I tried the 2nd choice,bit its not working for 1.2 & 1.4
-
October 30th, 2002, 05:45 AM
#5
Originally posted by Kohinoor24
I tried the 2nd choice,bit its not working for 1.2 & 1.4
It is not clear what “not working” means. I did not check the code, but it should work. If you have rounding problems you may add/subtract 0.5:
Code:
int i = int(10. * 0.39); // i == 3
int j = int(10. * 0.39 + 0.5); // j == 4
Regards,
Last edited by zdf; October 30th, 2002 at 05:47 AM.
ZDF
What is good is twice as good if it's simple.
"Make it simple" is a complex task.
-
October 30th, 2002, 06:47 AM
#6
soln
#include "stdio.h"
void main()
{
double i= 23.55;
char temp[10], temp1[10];
int val1, val2;
sprintf(temp,"%.2f",i);
for (int j=0;((temp1[j]=temp[j])!='\0')&&(temp[j]!='.');j++);
if (temp1[j]=='\0')
{
sscanf(temp1,"%d",&val1);
val2=0;
}
else
{
temp1[j]='\0';
sscanf(temp1,"%d",&val1);
j++;
for (int k=0;((temp1[k]=temp[j])!='\0');j++,k++);
sscanf(temp1,"%d",&val2);
}
/* val1 contains integer & val2 contains fraction*/
}
regards,
sursura
-
October 30th, 2002, 07:05 AM
#7
Maybe this would be a bit easier...
// Value to be "split"
float value (1.999);
// Set the decimal precision
int precision(2);
int integer= (int) value;
int fraction = (int) ((value - integer)*pow(10, precision));
// integer = 1 and fraction = 99
Villemos.
Last edited by villemos; October 30th, 2002 at 11:02 AM.
-
October 30th, 2002, 11:12 AM
#8
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|