From 1b2d7a004c1061a65e774efab8558b980f950410 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Mon, 9 Dec 2024 10:15:20 -0500 Subject: [PATCH] Show inches as mixed fraction in ArchUnits --- SawCut/ArchUnits.cs | 6 ++---- SawCut/Helper.cs | 49 ++++++++++++++++++++++++++++++++++++++++++++ SawCut/SawCut.csproj | 1 + 3 files changed, 52 insertions(+), 4 deletions(-) create mode 100644 SawCut/Helper.cs diff --git a/SawCut/ArchUnits.cs b/SawCut/ArchUnits.cs index d31867d..5bbf4fc 100644 --- a/SawCut/ArchUnits.cs +++ b/SawCut/ArchUnits.cs @@ -60,13 +60,11 @@ namespace SawCut public static string FormatFromInches(double totalInches) { var feet = Math.Floor(totalInches / 12.0); - var inches = totalInches - (feet * 12.0); - - inches = Math.Round(inches, 8); + var inches = Helper.ConvertToMixedFraction(totalInches - (feet * 12.0)); if (feet > 0) { - return $"{feet}'-{inches}\""; + return $"{feet}' {inches}\""; } else { diff --git a/SawCut/Helper.cs b/SawCut/Helper.cs new file mode 100644 index 0000000..a84ffa5 --- /dev/null +++ b/SawCut/Helper.cs @@ -0,0 +1,49 @@ +using System; +using System.Drawing; + +namespace SawCut +{ + public static class Helper + { + public static string ConvertToMixedFraction(decimal input, int precision = 32) + { + // Get the whole number part + int wholeNumber = (int)input; + + // Get the fractional part + decimal fractionalPart = Math.Abs(input - wholeNumber); + + if (fractionalPart == 0) + { + return wholeNumber.ToString(); + } + + // Convert the fractional part to a fraction + int numerator = (int)(fractionalPart * precision); + int denominator = precision; + + // Simplify the fraction + int gcd = GetGreatestCommonDivisor(numerator, denominator); + numerator /= gcd; + denominator /= gcd; + + return $"{wholeNumber}-{numerator}/{denominator}"; + } + + public static string ConvertToMixedFraction(double input) + { + return ConvertToMixedFraction((decimal)input); + } + + private static int GetGreatestCommonDivisor(int a, int b) + { + while (b != 0) + { + int temp = b; + b = a % b; + a = temp; + } + return Math.Abs(a); + } + } +} \ No newline at end of file diff --git a/SawCut/SawCut.csproj b/SawCut/SawCut.csproj index 8d7c863..bae08a7 100644 --- a/SawCut/SawCut.csproj +++ b/SawCut/SawCut.csproj @@ -46,6 +46,7 @@ +