public static string ToFraction(long integer, long numerator, long denominator, FractionalizeOptions options = null) { if (options == null) { options = new FractionalizeOptions(); } return(FormatResult(Math.Abs(integer), numerator, denominator, options, integer < 0)); }
public static string ToFraction(double number, FractionalizeOptions options = null) { if (options == null) { options = new FractionalizeOptions(); } lock (DenominatorMap) { if (DenominatorMap.Count < options.MaxDenominator) { CreateDenominatorMap(options.MaxDenominator); } } if (number > long.MinValue && number < long.MaxValue) { var isNegative = number < 0; var decimalPortion = Math.Abs(number) - Math.Truncate(Math.Abs(number)); var integerPortion = Convert.ToInt64(Math.Floor(Math.Abs(number))); for (var i = 0; i < options.MaxDenominator; ++i) { lock (DenominatorMap) { for (var j = 0; j < DenominatorMap[i].Count; ++j) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (decimalPortion == DenominatorMap[i][j]) { return(FormatResult(integerPortion, j + 1, i + 1, options, isNegative)); } } } } if (!options.ExactMatch) { for (var i = 0; i < options.MaxDenominator; ++i) { lock (DenominatorMap) { for (var j = 0; j < DenominatorMap[i].Count; ++j) { if (decimalPortion + options.Tolerance > DenominatorMap[i][j] && decimalPortion - options.Tolerance < DenominatorMap[i][j]) { return(FormatResult(integerPortion, j + 1, i + 1, options, isNegative, true)); } } } } } } return(number.ToString(options.Culture)); }
public static string ToFraction(float number, FractionalizeOptions options = null) { return(ToFraction(Convert.ToDouble(number), options)); }
public static string ToFraction(string number, FractionalizeOptions options = null) { return(ToFraction(Convert.ToDouble(number, options?.Culture), options)); }
private static string FormatResult(long integerPortion, long numerator, long denominator, FractionalizeOptions options, bool isNegative, bool isApproximate = false) { if (UnicodeMap.ContainsKey(denominator) && UnicodeMap[denominator].ContainsKey(numerator)) { return(String.Join("", isApproximate && options.ShowApproximationSymbol ? "\u2248" : "", isNegative ? "-":"", integerPortion != 0 ? integerPortion.ToString() : "", integerPortion != 0 && options.SpaceBetweenIntegerAndFraction ? " " : "", UnicodeMap[denominator][numerator].ToString())); } return(String.Join("", isApproximate && options.ShowApproximationSymbol ? "\u2248" : "", isNegative ? "-":"", integerPortion != 0 ? integerPortion.ToString() : "", integerPortion != 0 && options.SpaceBetweenIntegerAndFraction ? " " : "", numerator.ToString(), "/", denominator.ToString())); }
public static string ToFraction(this double number, FractionalizeOptions options = null) { return(Fractionalize.ToFraction(number, options)); }
public static string ToFraction(this decimal number, FractionalizeOptions options = null) { return(Fractionalize.ToFraction(Convert.ToDouble(number), options)); }