Click to See Complete Forum and Search --> : Seperating Integer & Fractional Part


Kohinoor24
October 30th, 2002, 02:27 AM
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...

SreeDharan
October 30th, 2002, 03:41 AM
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

zdf
October 30th, 2002, 03:52 AM
Try:

double d, ip;
d = 1.4
int fp = 10 * modf( d, &ip );

Regards,

Kohinoor24
October 30th, 2002, 04:09 AM
I tried the 2nd choice,bit its not working for 1.2 & 1.4

zdf
October 30th, 2002, 04:45 AM
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:

int i = int(10. * 0.39); // i == 3
int j = int(10. * 0.39 + 0.5); // j == 4

Regards,

sursura
October 30th, 2002, 05:47 AM
#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

villemos
October 30th, 2002, 06:05 AM
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.

Kohinoor24
October 30th, 2002, 10:12 AM
Thanks...