You want to return a fractional approximation from a real number? e.g. 0.3333 ~ "1/3". You could try experimenting with this:
#import <Foundation/Foundation.h>
char out[20];
static char *fractApprox(double r, long d) {
double atof();
int atoi();
void exit();
long m[2][2];
double x, startx;
long maxden;
long ai;
startx = x = r;
maxden = d;
/* initialize matrix */
m[0][0] = m[1][1] = 1;
m[0][1] = m[1][0] = 0;
/* loop finding terms until denom gets too big */
while (m[1][0] * ( ai = (long)x ) + m[1][1] <= maxden) {
long t;
t = m[0][0] * ai + m[0][1];
m[0][1] = m[0][0];
m[0][0] = t;
t = m[1][0] * ai + m[1][1];
m[1][1] = m[1][0];
m[1][0] = t;
if(x==(double)ai) break; // AF: division by zero
x = 1/(x - (double) ai);
if(x>(double)0x7FFFFFFF) break; // AF: representation failure
}
ai = (maxden - m[1][1]) / m[1][0];
m[0][0] = m[0][0] * ai + m[0][1];
m[1][0] = m[1][0] * ai + m[1][1];
sprintf(out, "%ld/%ld",m[0][0],m[1][0]);
return out;
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
printf("%s",fractApprox(0.342343, 999));
}
return 0;
}
Prints 329/961
to the console.
Credits to David Eppstein, UC Irvine for the algorithm in C