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


as part of calculator app, trying implement uses sigma notation. however, result prints out decimal, , rest isn't important. want change decimal fraction.

i have reduce function, problem i'm having getting decimal this: '0.96875' it's fractional value, '31/32'

thanks!

ps: i've looked everything, , life of me, can't figure out. need @ point how take decimal out of it, , can reduce it.

here 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;  } 

found out myself. did multiply numerator , denominator 1000000 (recalling decimal looked .96875/1) looked 96875/100000.

then, used reduce method bring 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 print method fraction form:

//in .h @property int numerator, denominator, mixed; -(void)print;  //in .m        @synthesize numerator, denominator, mixed;  -(void)print {     if (numerator > denominator) {         //turn fraction mixed number         mixed = numerator/denominator;         numerator -= (mixed * denominator);         nslog(@"= %i %i/%i", mixed, numerator, denominator);     } else if (denominator != 1) {         //print fraction         nslog(@"= %i/%i", numerator, denominator);     } else {         //print integer if has denominator of 1         nslog(@"= %i", numerator);     } } 

and got desired output:

31/32 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -