Convert decimal to fractions in Objective-C?

I try to take everything after a decimal fraction and show it as a fraction. Could not find much for objective-c on how to do this. I use double for my formatting variables, not sure if it matters or not. Here's how I format it to display my answer: [theTextField setText:[NSString stringWithFormat:@"%f''", (myVariable)]]; This displays ok as a decimal, but it really will like it as an integer and a fraction (i.e.) of 7 1/2 instead of 7.5000. Thank you for your help!

Update: 5/13/2011

Ok, I got it to display 7 1/16, but something with math is disabled. Because it will not change from 1/16, even changing the values ​​that become divided. Where am I wrong here? If someone can really make it work, please write in full how to do it. This is something that should be simple, but not too or too laborious. Please fully publish how this is done. Thank you

Update: If this answer does not work, you check my other post, it works! Convert decimals to fractions

+8
formatting objective-c iphone xcode
source share
2 answers

Objective-C uses pure C for all primitive math operations.

In this case, you will find all the necessary information (along with the C code) in the answers to this other question:

How to convert floats into human readable fractions?

(In particular, this answer containing the actual C code .)

Here is a quick c-function wrapper for the specified algorithm:

 typedef struct { long nominator; long denominator; double error; } Fraction; /* * Find rational approximation to given real number * David Eppstein / UC Irvine / 8 Aug 1993 * * With corrections from Arno Formella, May 2008 * Function wrapper by Regexident, April 2011 * * usage: fractionFromReal(double realNumber, long maxDenominator) * realNumber: is real number to approx * maxDenominator: is the maximum denominator allowed * * based on the theory of continued fractions * if x = a1 + 1/(a2 + 1/(a3 + 1/(a4 + ...))) * then best approximation is found by truncating this series * (with some adjustments in the last term). * * Note the fraction can be recovered as the first column of the matrix * ( a1 1 ) ( a2 1 ) ( a3 1 ) ... * ( 1 0 ) ( 1 0 ) ( 1 0 ) * Instead of keeping the sequence of continued fraction terms, * we just keep the last partial product of these matrices. */ Fraction fractionFromReal(double realNumber, long maxDenominator) { double atof(); int atoi(); void exit(); long m[2][2]; double startx; long ai; startx = realNumber; // 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)realNumber) + m[1][1] <= maxDenominator) { 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 (realNumber == (double)ai) { // AF: division by zero break; } realNumber = 1 / (realNumber - (double)ai); if (realNumber > (double)0x7FFFFFFF) { // AF: representation failure break; } } ai = (maxDenominator - 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]; return (Fraction) { .nominator = m[0][0], .denominator = m[1][0], .error = startx - ((double)m[0][0] / (double)m[1][0]) }; } 

Call it like this:

 double aReal = 123.45; long maxDenominator = 42; Fraction aFraction = fractionFromReal(aReal, maxDenominator); printf("Real %.3f -> fraction => %ld/%ld, error: %.3f\n", aReal, aFraction.nominator, aFraction.denominator, aFraction.error); 

Will print this:

 Real 123.450 -> fraction => 3827/31, error: -0.002 

Last but not least, let's see how we get our recently processed fraction into the text box:

 double myVariable = 7.5; long maxDenominator = 1000; //sample value Fraction myFraction = fractionFromReal(abs(myVariable - (NSInteger)myVariable), maxDenominator); [theTextField setText:[NSString stringWithFormat:@"%d %d/%d", (NSInteger)myVariable, myFraction.nominator, myFraction.denominator]]; 

Expected Result: "7 1/2" , Actual Result: "7 499/999"
For information on why this can happen, see the answer to the corresponding question: How to convert floats into human readable fractions?

+8
source share

I wrote code to convert the decimal fraction to its smallest fraction possible. This works great.

 -(int)gcdForNumber1:(int) m andNumber2:(int) n { while( m!= n) // execute loop until m == n { if( m > n) m= m - n; // large - small , store the results in large variable<br> else n= n - m; } return ( m); // m or n is GCD } -(int)tenRaisedTopower:(int)decimalLength { int answer = 10; while (decimalLength!= 1) { answer *= 10; decimalLength -- ; } return answer; } -(void)floatToFraction:(float)decimalNumber { NSString *decimalString = [NSString stringWithFormat:@"%f", decimalNumber]; NSArray *components = [decimalString componentsSeparatedByString:@"."]; int decimalLength = [[components objectAtIndex:1] length]; int n = [self tenRaisedTopower:decimalLength]; int m = [[components objectAtIndex:1] intValue]; int gcd = [self gcdForNumber1:m andNumber2:n]; int numer = m/gcd; int deno = n/gcd; int fractionnumer = ([[components objectAtIndex:0] intValue] * deno) + numer; NSLog(@"answer>>%d/%d", fractionnumer, deno); } 

call method:

 [self floatToFraction:2.5]; 
+6
source share

All Articles