user2252471 - 1 month ago 5x
Swift Question

# Pi Output In Swift

I am trying to build a degrees/radians calculator. Here are the functions I have.

``````func degreesToRadians(degrees: Double) -> Double {

return degrees * (M_PI / 180)

}

return radians * (180 / M_PI)

}

``````

What I want to happen is in the Degrees to Radians function instead of 1.5707963267949 I want the output to be π/2. Is this even possible?

Thanks.

To represent `90` degrees as `π/2`, what you want to do is

• consider the fraction of `degrees` over 180 (i.e. numerator of `degrees` and denominator of `180`);

• reduce this fraction (i.e. divide both the numerator and denominator by the greatest common factor); in the case of `90/180`, the greatest common factor is, in fact, `90`, yielding a reduced numerator of `1` and a reduced denominator of `2`;

• the result as a string representation of the fraction, i.e. something like

``````"\(reducedNumerator)π/\(reducedDenominator)"
``````

Obviously, if either the numerator or denominator are `1`, then you can suppress that portion of the string, but hopefully you get the basic idea.

Take a crack at that.

Source (Stackoverflow)