Search code examples
objective-cmathrational-numbers

Convert decimal to fraction (rational number) in Objective C?


As part of a calculator app, I am trying to implement uses with sigma notation. However, the result it prints out is always a decimal, and the rest isn't important. I simply want to change the decimal to a fraction.

I already have the reduce function, the problem I'm having is getting from a decimal like this: '0.96875' to it's fractional value, '31/32'

Thanks!

PS: I've looked into just about everything, and for the life of me, I can't figure this out. All I need at this point is how to take the decimal out of it, and I can then reduce it.

Here is my reduce method:

    -(void)reduce {

    int u = numerator;
    int v = denominator;
    int temp;

    while (v != 0) {
        temp = u % v;
        u = v;
        v = temp;
    }

    numerator /= u;
    denominator /= u;

}

Solution

  • Found this out myself. What I did was multiply the numerator and denominator by 1000000 (recalling that the decimal looked like .96875/1) so that it looked like 96875/100000.

    Then, I used this reduce method to bring it into lowest terms:

        -(void)reduce {
    
        int u = numerator;
        int v = denominator;
        int temp;
    
        while (v != 0) {
            temp = u % v;
            u = v;
            v = temp;
        }
    
        numerator /= u;
        denominator /= u;
    
    }
    

    And finally,I used a print method to get it into fraction form:

    //In the .h
    @property int numerator, denominator, mixed;
    -(void)print;
    
    //In the .m       
    @synthesize numerator, denominator, mixed;
    
    -(void)print {
        if (numerator > denominator) {
            //Turn fraction into mixed number
            mixed = numerator/denominator;
            numerator -= (mixed * denominator);
            NSLog(@"= %i %i/%i", mixed, numerator, denominator);
        } else if (denominator != 1) {
            //Print fraction normally
            NSLog(@"= %i/%i", numerator, denominator);
        } else {
            //Print as integer if it has a denominator of 1
            NSLog(@"= %i", numerator);
        }
    }
    

    And got my desired output:

    31/32