How do I work with fractions and precision

Working with fractions in C# can be simplified using the `Fraction` class, which allows you to represent a fraction as a numerator and a denominator. Additionally, precision is crucial, especially when dealing with mathematical operations. Below is an example of a custom `Fraction` class that ensures proper handling of fractions and maintains precision.

// C# example of a simple Fraction class public class Fraction { public int Numerator { get; private set; } public int Denominator { get; private set; } public Fraction(int numerator, int denominator) { if (denominator == 0) throw new ArgumentException("Denominator cannot be zero."); Numerator = numerator; Denominator = denominator; Reduce(); } private void Reduce() { int gcd = GCD(Numerator, Denominator); Numerator /= gcd; Denominator /= gcd; } private int GCD(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return Math.Abs(a); } public override string ToString() { return $"{Numerator}/{Denominator}"; } } // Usage example var fraction = new Fraction(3, 9); Console.WriteLine(fraction); // Outputs: 1/3

fractions C# precision custom class reduce fractions mathematical operations