An extension for floating point values to return the rational components for that value
/// Swift example
let rational = -9.90.rationalValue
// result.fraction, -9.90)
// result.description, "-9 9/10")
// result.whole, -9)
// result.numerator, 9)
// result.denominator, 10)
/// Objective-C example
id<RationalRepresentation> result = [DSFRational valueFor:-11.112];
assert([[result description] isEqual:@"-11 14/125"]);
assert([result whole] == -11);
assert([result numerator] == 14);
assert([result denominator] == 125);
assert([result fraction] == -11.112);
The algorithm arises from a comment on GameDev.net by user John Bolton.
Here is an algorithm for converting a value to the closest fraction (given a maximum value for the denominator). It is based on Farey Sequences. It is probably much faster than finding GCDs and the results are much more useful. For example, using the suggestions above, .333333 will be converted to 333333/1000000, which is probably not what you want. Using this algorithm, you will get 1/3.