using System;
namespace CutList.Core
{
///
/// Provides formatting utilities for displaying measurements and values.
///
public static class FormatHelper
{
///
/// Converts a decimal measurement to a mixed fraction string representation.
///
/// The decimal value to convert
/// The denominator precision (default 16 for 1/16")
/// A string in the format "whole-numerator/denominator"
public static string ConvertToMixedFraction(decimal input, int precision = 16)
{
// 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;
// If rounding wiped out the fraction → return whole number only
if (numerator == 0)
{
return wholeNumber.ToString();
}
return $"{wholeNumber}-{numerator}/{denominator}";
}
///
/// Converts a double measurement to a mixed fraction string representation.
///
/// The double value to convert
/// A string in the format "whole-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);
}
}
}