Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

In C how to extract the integer and decimal part from a float number

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I want a C code which extracts the integer and decimal part separately from a float number.
Please help!!
 
hi,
Try this code.its very native but works ok.

void main(void)
{
float f=43.344;

int x=int(f);
float d=f-x;

printf(" %d %f", x,d);
}

yogesh
 
It works only if f>=0
hnd
hasso55@yahoo.com

 
no the program runs for negative floating point numbers also

try with f=-456.34;
 
Thanks a lot hawapani.. But I wanted to know how to get it, with mod 10 0r by dividing by 10.
 
Thanks a lot hawapani.. But I wanted to know how to get it, with mod 10 0r by dividing by 10.
 
okay I have just written a similar function to print a value held on file and output it to a print record thru PRN.
I am sure if you read the function you may be able to adjust it to your rquirements.

the following takes a double value - say 123456.12 - and prints to the print report in the form of 123,456.12.

void monetary_balance (double bal_val)
{
const long test1 = 100000000L, test2 = 100000L,
grand = 1000L, tun = 100L;
long under100 = 0L, under1000 = 0L, undermill = 0L,
convertval = 0L, overmill = 0L;

bal_val *= 100; //
convertval = (long)bal_val;

if(convertval > test1)
{
under100 = convertval % tun;
under1000 = convertval % test2;
under1000 = under1000 / tun;
undermill = convertval / test2;
undermill = undermill % grand;
overmill = convertval / test1;
fprintf(prnt,"%ld,%3ld,%3ld.%2ld \n\n", overmill, undermill, under1000, under100);
}
else if(convertval > test2)
{
under100 = convertval % tun;
under1000 = convertval % test2;
under1000 = under1000 / tun;
undermill = convertval / test2;
fprintf(prnt,"%ld,%3ld.%2ld \n\n", undermill, under1000, under100);
}
else
{
under100 = convertval % tun;
under1000 = convertval % test2;
under1000 = under1000 / tun;
fprintf(prnt,"%ld.%2ld \n\n", under1000, under100);
}
} /* end function monetary_balance */

THIS DOESNOT WORK FOR NEGATIVE NUMBERS Hoping to get certified..in C programming.
 
Ok,

Here is a code snippet that will rip apart the int and the fraction part of a floating number.

Code:
float f_no=-123.45;
int i_no, i_dec;

i_no=(int)f_no;
i_dec=abs((f_no-(int)f_no)*10e5);

printf("Integer part=%d and fraction=%d",i_no,i_dec);

Note: In 10e5, 5 is the number of decimals you would want to see, you can reduce or increase it as per the precision you want to work with.

I hope that was clear...;-)

Roy.

user.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top