0

Possible Duplicate:
Convert decimal to fraction in Objective-C?

I'm trying to make an simple app for converting decimal form to fraction form. The decimal value is set to a UISlider“s value but how should I get the fraction in fraction form? Should I declare it with double or float and how should I tell the app to print it out in fraction form?

Community
  • 1
  • 1
wmichaelsen
  • 549
  • 1
  • 6
  • 14

2 Answers2

0

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

FluffulousChimp
  • 9,157
  • 3
  • 35
  • 42
0

What you need to convert a decimal to fraction is GCD. For example: 0.535

  1. 0.535 => 535/1000
  2. GCD(535, 1000) => 5
  3. (535/5) / (1000/5) => 107/200.
sunkehappy
  • 8,970
  • 5
  • 44
  • 65