// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; namespace E { public class Program { public static string FormatFraction(double x) { int ipart = (int)x; double fpart = x - ipart; for(int i = 2; i < 100; i++) { double scaledf = fpart * i; if(Math.Abs(scaledf - (int)scaledf) < 0.0001) { if(ipart > 0) { return ipart + " " + (int)scaledf + "/" + i; } else { return (int)scaledf + "/" + i; } } } throw new ArgumentException("Not a simple fraction: " + x); } public static void Main(string[] args) { Console.WriteLine(FormatFraction(1.25)); Console.WriteLine(FormatFraction(2.625)); Console.WriteLine(FormatFraction(1.0/3)); } } }