I am trying to take everything after the decimal and display it as a fraction. Couldn't find much for objective-c on how to accomplish this. I am using double
for my formatting of variables, not sure if that would matter or not. This is how I am formatting for output of my answer:[theTextField setText:[NSString stringWithFormat:@"%f''", (myVariable)]];
This displays ok as decimal, but would really like it as a whole number and fraction (ie.) 7 1/2 instead of 7.5000. Thank you in advanced!
Update:5/13/2011
Well, I got it to display 7 1/16, but something with the math is off. Because it won't change from 1/16 even by changing the values that are getting divided. Where am I going wrong here? If anyone can actually get this to work correctly please post fully how its done. This is something that should be simple but isn't and way too time consuming. Please post fully how it is done. Thanks.
Update: If this answer isn't working for you check out my other post, this works! Convert decimals to fractions
I have written code to convert decimal to its lowest possible fraction. This works perfectly well.
call method as:
Objective-C uses pure C for basically all primitive mathematical operations.
This being said you'll find all necessary information (along with C code) in the answers of this other question:
How to convert floats to human-readable fractions?
(Specifically this answer featuring actual C code.)
Here is a quick c function wrapper of said algorithm:
Calling it like this:
Prints this:
Last but not least let's see how we get our newly crafted fraction into out text field:
Expected output:
"7 1/2"
, actual output:"7 499/999"
For some info on why this can happen see this answer to a related question: How to convert floats to human-readable fractions?