This topic is now archived and is closed to further replies.


fraction problems

Recommended Posts

hello everyone! i have a variable called num that is a double. trying to seperate num into integer and the fraction: int int_num = num; double fraction = num - int_num. the problem is that when i input for exapmle: 34.45 int_num gets 34 but fraction gets 0.44999999... is there a way to fix this?

Share this post

Link to post
Share on other sites
Guest Anonymous Poster
There''s no way to fix it, unless you make your own number type . Representing 34.45 with a double leads to unprecise results. But do you really need to fix it? What are you trying to do?

Share this post

Link to post
Share on other sites
Alternatively, If you know the maximum number of decimal places, try something like this ...

double fNum = 34.45;
int nNum;
double fFraction;
int nFraction;

nNum = long(fNum) * 10000
nFraction = fNum * 10000 - nNum
fFraction = double(nFraction) * 10000

Obviously it's only accurate up to a certain number of digits, depends what you want.


[edited by - Shag on November 2, 2002 12:25:55 PM]

Share this post

Link to post
Share on other sites
i'm with petewood here.

#define PRESCISION 1000000.0

int CountOccurences(const double& dNum, char chFind)
char szBuff[64];
char* pBuff;
int nCount = 0;

pBuff = szBuff;
while(*pBuff != '\0')
if(*pBuff == chFind)
return nCount;

Edit: Damn [ source ]tags...

HTH, Steve

DirectX Programmer
Soon to be the new Bill Gates

[edited by - Evil Bill on November 3, 2002 4:24:32 PM]

Share this post

Link to post
Share on other sites
Actually, there are standard C math library functions for this purpose: frexp(),ldexp(), and modf(). To get both the the characteristic (the integer part) and the mantissa (the fractional part), you'd need to do something like this:

#include <math.h>

double value = 3.14159265358979;
double characteristic, mantissa;
long count;

mantissa = modf(value, &characteristic);
//returns 0.14159265358979 to mantissa, sets characteristic to 3.0

count = (long) characteristic;

You can use int instead of long, but I recommend using a long in case it is a very large value. To use frexp() to do the same thing, you'd change it so that:

double exponent;

mantissa = frexp(value, &exponent);
// returns 0.14159265358979 to mantissa, sets exponent

// to the binary power of the characteristic

characteristic = pow(2, exponent);

Finally, if you want to get just the exponent, then you should use

count = (int) floor(d);

to ensure that the cast value is truncated rather than rounded to the nearest integer (this assumes that all values in question are positive).

Note that this code is not actually tested. You will probably have to make some minor modifications to get it to work as you need it to.

Trouble rather the tiger in his lair than the Scholar among his books

[edited by - Schol-R-LEA on November 6, 2002 5:12:21 PM]

Share this post

Link to post
Share on other sites