Fraction<T> Struct
Definition
- Assembly
- Bodu.Numerics.dll
- Package
- Bodu.Numerics 1.0.0
Represents an immutable exact rational number - a ratio of two integers - backed by an arbitrary IBinaryInteger<TSelf> component type.
public readonly struct Fraction<T> : INumber<Fraction<T>>, IComparable, IComparable<Fraction<T>>, IComparisonOperators<Fraction<T>, Fraction<T>, bool>, IModulusOperators<Fraction<T>, Fraction<T>, Fraction<T>>, ISignedNumber<Fraction<T>>, INumberBase<Fraction<T>>, IEquatable<Fraction<T>>, ISpanFormattable, IFormattable, ISpanParsable<Fraction<T>>, IParsable<Fraction<T>>, IUtf8SpanFormattable, IUtf8SpanParsable<Fraction<T>>, IAdditionOperators<Fraction<T>, Fraction<T>, Fraction<T>>, IAdditiveIdentity<Fraction<T>, Fraction<T>>, IDecrementOperators<Fraction<T>>, IDivisionOperators<Fraction<T>, Fraction<T>, Fraction<T>>, IEqualityOperators<Fraction<T>, Fraction<T>, bool>, IIncrementOperators<Fraction<T>>, IMultiplicativeIdentity<Fraction<T>, Fraction<T>>, IMultiplyOperators<Fraction<T>, Fraction<T>, Fraction<T>>, ISubtractionOperators<Fraction<T>, Fraction<T>, Fraction<T>>, IUnaryNegationOperators<Fraction<T>, Fraction<T>>, IUnaryPlusOperators<Fraction<T>, Fraction<T>> where T : IBinaryInteger<T>
Type Parameters
TThe integer type used to store the numerator and denominator.
- Implements
-
IComparable<Fraction<T>>INumberBase<Fraction<T>>IEquatable<Fraction<T>>
- Inherited Members
- Extension Methods
Examples
// Construct from components; the value is reduced to canonical form on creation.
Fraction<int> oneHalf = new Fraction<int>(2, 4); // 1/2
Fraction<int> oneThird = new Fraction<int>(1, 3);
// Exact arithmetic through the operators.
Fraction<int> sum = oneHalf + oneThird; // 5/6
// Parse and format round-trip through the invariant "numerator/denominator" form.
Fraction<int> parsed = Fraction<int>.Parse("3/8");
string text = parsed.ToString(); // "3/8"
Remarks
A Fraction<T> is always held in canonical form: the denominator is strictly positive, the numerator carries the sign, and the two components share no common factor other than one. Equal rational values therefore have identical components and compare and hash equally.
Choose a fixed-width T such as int or long for compact
storage, or BigInteger for arithmetic that never overflows.
Arithmetic is exact. Intermediate results are evaluated with BigInteger precision and the canonical
result is narrowed back to T; when the narrowed component does not fit a fixed-width
T an OverflowException is thrown. Selecting BigInteger as
T removes that limit entirely.
When T is an unsigned integer type, negative rationals cannot be represented; operations
that would produce a negative component - such as negating a non-zero value - throw an
OverflowException at run time.
Constructors
Fraction(T)
Initializes a new instance of the Fraction<T> struct representing the whole number
value.
public Fraction(T value)
Parameters
valueTThe integer value the fraction represents.
Fraction(T, T)
Initializes a new instance of the Fraction<T> struct from the specified numerator and denominator, reducing the result to canonical form.
public Fraction(T numerator, T denominator)
Parameters
numeratorTThe numerator of the rational value.
denominatorTThe denominator of the rational value.
Exceptions
- DivideByZeroException
Thrown if
denominatoris zero.- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
T.
Properties
Denominator
Gets the denominator of the rational value in canonical form.
public T Denominator { get; }
Property Value
- T
A value of one is reported for a default-initialized instance so that
default(Fraction<T>)behaves as the rational value zero.
IsCanonical
Gets a value indicating whether this rational value is in canonical form.
public bool IsCanonical { get; }
Property Value
IsEvenInteger
Gets a value indicating whether this rational value is an even integer.
public bool IsEvenInteger { get; }
Property Value
IsImproper
Gets a value indicating whether this rational value is an improper fraction.
public bool IsImproper { get; }
Property Value
IsInteger
Gets a value indicating whether this rational value is an exact integer.
public bool IsInteger { get; }
Property Value
IsNegative
Gets a value indicating whether this rational value is negative.
public bool IsNegative { get; }
Property Value
IsOddInteger
Gets a value indicating whether this rational value is an odd integer.
public bool IsOddInteger { get; }
Property Value
IsPositive
Gets a value indicating whether this rational value is positive.
public bool IsPositive { get; }
Property Value
IsProper
Gets a value indicating whether this rational value is a proper fraction.
public bool IsProper { get; }
Property Value
IsReducible
Gets a value indicating whether this rational value can be reduced to lower terms.
public bool IsReducible { get; }
Property Value
IsUnit
Gets a value indicating whether this rational value is a unit fraction.
public bool IsUnit { get; }
Property Value
IsWhole
Gets a value indicating whether this rational value is a whole number.
public bool IsWhole { get; }
Property Value
Remarks
This property is an alias for IsInteger.
IsZero
Gets a value indicating whether this rational value is zero.
public bool IsZero { get; }
Property Value
MaxValue
Gets the largest finite value a Fraction<T> backed by T can represent.
public static Fraction<T> MaxValue { get; }
Property Value
- Fraction<T>
The rational value
T.MaxValue/1.
Remarks
A bound exists only when T implements IMinMaxValue<TSelf>. Unbounded
backing types model the full set of rationals and therefore have no maximum value.
Exceptions
- NotSupportedException
Thrown if
Tis an unbounded integer type, such as BigInteger.
MinValue
Gets the smallest finite value a Fraction<T> backed by T can represent.
public static Fraction<T> MinValue { get; }
Property Value
- Fraction<T>
The rational value
T.MinValue/1.
Remarks
A bound exists only when T implements IMinMaxValue<TSelf>. Unbounded
backing types model the full set of rationals and therefore have no minimum value.
Exceptions
- NotSupportedException
Thrown if
Tis an unbounded integer type, such as BigInteger.
MinusOne
Gets a Fraction<T> representing the value negative one.
public static Fraction<T> MinusOne { get; }
Property Value
- Fraction<T>
The rational value
-1/1.
Exceptions
- OverflowException
Thrown if
Tis an unsigned type and cannot represent-1.
Numerator
Gets the numerator of the rational value in canonical form.
public T Numerator { get; }
Property Value
- T
The signed numerator.
Sign
Gets the sign of the rational value.
public int Sign { get; }
Property Value
- int
-1if the value is negative,0if the value is zero, and1if the value is positive.
Methods
Abs()
Returns the absolute value of this rational value.
public Fraction<T> Abs()
Returns
- Fraction<T>
The canonical magnitude of this value.
Exceptions
- OverflowException
Thrown if the magnitude of the numerator cannot be represented by
T.
Add(Fraction<T>, Fraction<T>)
Adds two rational values.
public static Fraction<T> Add(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical sum of
leftandright.
Examples
var a = Fraction<int>.Parse("1/2");
var b = Fraction<int>.Parse("1/4");
var sum = Fraction<int>.Add(a, b); // 3/4
var difference = Fraction<int>.Subtract(a, b); // 1/4
var product = Fraction<int>.Multiply(a, b); // 1/8
var quotient = Fraction<int>.Divide(a, b); // 2
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
Approximate(decimal, T)
Returns the closest rational approximation of a decimal value within a denominator bound.
public static Fraction<T> Approximate(decimal value, T maxDenominator)
Parameters
valuedecimalThe value to approximate.
maxDenominatorTThe largest denominator the approximation may use.
Returns
- Fraction<T>
The best rational approximation of
valuewith a denominator no greater thanmaxDenominator.
Exceptions
- ArgumentOutOfRangeException
Thrown if
maxDenominatoris less than one.- OverflowException
Thrown if the canonical result cannot be represented by
T.
Approximate(double, T)
Returns the closest rational approximation of a double-precision value within a denominator bound.
public static Fraction<T> Approximate(double value, T maxDenominator)
Parameters
valuedoubleThe value to approximate.
maxDenominatorTThe largest denominator the approximation may use.
Returns
- Fraction<T>
The best rational approximation of
valuewith a denominator no greater thanmaxDenominator.
Exceptions
- ArgumentException
Thrown if
valueis not a finite number.- ArgumentOutOfRangeException
Thrown if
maxDenominatoris less than one.- OverflowException
Thrown if the canonical result cannot be represented by
T.
Approximate(string, T, IFormatProvider?)
Returns the closest rational approximation of a numeric string within a denominator bound.
public static Fraction<T> Approximate(string value, T maxDenominator, IFormatProvider? provider = null)
Parameters
valuestringThe decimal-format text to approximate.
maxDenominatorTThe largest denominator the approximation may use.
providerIFormatProviderThe culture used to interpret
value.
Returns
- Fraction<T>
The best rational approximation of
valuewith a denominator no greater thanmaxDenominator.
Exceptions
- ArgumentNullException
Thrown if
valueis null.- ArgumentOutOfRangeException
Thrown if
maxDenominatoris less than one.- FormatException
Thrown if
valueis not a valid decimal number.- OverflowException
Thrown if
valueor the canonical result is out of range.
As<TOther>()
Converts this rational value to an equivalent Fraction<T> over a different backing integer type.
public Fraction<TOther> As<TOther>() where TOther : IBinaryInteger<TOther>
Returns
- Fraction<TOther>
A Fraction<T> with the same canonical value.
Type Parameters
TOtherThe backing integer type of the result.
Exceptions
- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
TOther.
Ceiling()
Returns the smallest integer rational value greater than or equal to this value.
public Fraction<T> Ceiling()
Returns
- Fraction<T>
This value rounded toward positive infinity.
Clamp(Fraction<T>, Fraction<T>, Fraction<T>)
Returns value constrained to the inclusive range bounded by two rational values.
public static Fraction<T> Clamp(Fraction<T> value, Fraction<T> min, Fraction<T> max)
Parameters
valueFraction<T>The value to clamp.
minFraction<T>The inclusive lower bound.
maxFraction<T>The inclusive upper bound.
Returns
- Fraction<T>
The clamped value, constrained to the inclusive range.
Exceptions
- ArgumentException
Thrown if
minis greater thanmax.
Compare(Fraction<T>, Fraction<T>)
Compares two rational values and indicates their relative order.
public static int Compare(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- int
A negative number if
leftprecedesright, zero if they are equal, and a positive number ifleftfollowsright.
CompareTo(Fraction<T>)
Compares this rational value with another and indicates their relative order.
public int CompareTo(Fraction<T> other)
Parameters
otherFraction<T>The value to compare with this value.
Returns
- int
A negative number if this value precedes
other, zero if they are equal, and a positive number if this value followsother.
CompareTo(object?)
Compares this rational value with the specified object and indicates their relative order.
public int CompareTo(object? obj)
Parameters
objobjectThe object to compare with this value.
Returns
- int
A negative number if this value precedes
obj, zero if they are equal, and a positive number if this value followsobj. A null object sorts before any value.
Exceptions
- ArgumentException
Thrown if
objis not a Fraction<T>.
Create(T, T)
Creates a canonical Fraction<T> from the specified numerator and denominator.
public static Fraction<T> Create(T numerator, T denominator)
Parameters
numeratorTThe numerator of the rational value.
denominatorTThe denominator of the rational value.
Returns
- Fraction<T>
The reduced rational value.
Exceptions
- DivideByZeroException
Thrown if
denominatoris zero.- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
T.
Cubed()
Returns the cube of this rational value.
public Fraction<T> Cubed()
Returns
- Fraction<T>
The canonical value of this rational raised to the third power.
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
Deconstruct(out T, out T)
Deconstructs the rational value into its canonical numerator and denominator.
public void Deconstruct(out T numerator, out T denominator)
Parameters
numeratorTWhen this method returns, contains the canonical numerator.
denominatorTWhen this method returns, contains the canonical denominator.
Deconstruct(out T, out T, out T)
Deconstructs this value into its integer part and the numerator and denominator of its fractional part.
public void Deconstruct(out T whole, out T numerator, out T denominator)
Parameters
wholeTWhen this method returns, contains the integer part, truncated toward zero.
numeratorTWhen this method returns, contains the signed numerator of the fractional part.
denominatorTWhen this method returns, contains the denominator of the fractional part.
Divide(Fraction<T>, Fraction<T>)
Divides one rational value by another.
public static Fraction<T> Divide(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical quotient
leftdivided byright.
Exceptions
- DivideByZeroException
Thrown if
rightis zero.- OverflowException
Thrown if the canonical result does not fit
T.
Equals(Fraction<T>)
Determines whether the specified Fraction<T> is equal to this value.
public bool Equals(Fraction<T> other)
Parameters
otherFraction<T>The value to compare with this value.
Returns
Equals(object?)
Determines whether the specified object is a Fraction<T> equal to this value.
public override bool Equals(object? obj)
Parameters
objobjectThe object to compare with this value.
Returns
- bool
true if
objis a Fraction<T> with the same canonical value; otherwise, false.
Floor()
Returns the largest integer rational value less than or equal to this value.
public Fraction<T> Floor()
Returns
- Fraction<T>
This value rounded toward negative infinity.
Examples
var value = Fraction<int>.Parse("7/2"); // 3.5
var floor = value.Floor(); // 3
var ceiling = value.Ceiling(); // 4
var truncated = value.Truncate(); // 3
var rounded = value.Round(); // 4 (ties resolved to the nearest even integer)
FromBigInteger(BigInteger, BigInteger)
Creates a canonical Fraction<T> from a numerator and denominator of arbitrary magnitude.
public static Fraction<T> FromBigInteger(BigInteger numerator, BigInteger denominator)
Parameters
numeratorBigIntegerThe numerator of the rational value.
denominatorBigIntegerThe denominator of the rational value.
Returns
- Fraction<T>
The reduced rational value narrowed to
T.
Exceptions
- DivideByZeroException
Thrown if
denominatoris zero.- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
T.
FromContinuedFraction(params T[])
Reconstructs a rational value from the coefficients of a simple continued fraction.
public static Fraction<T> FromContinuedFraction(params T[] coefficients)
Parameters
coefficientsT[]The continued-fraction coefficients. The leading coefficient may carry any sign; every following coefficient must be strictly positive.
Returns
- Fraction<T>
The canonical rational value the coefficients describe.
Exceptions
- ArgumentNullException
Thrown if
coefficientsis null.- ArgumentException
Thrown if
coefficientsis empty.- ArgumentOutOfRangeException
Thrown if a coefficient after the first is not strictly positive.
- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
T.
FromDecimal(decimal)
Converts a decimal to its exact rational representation.
public static Fraction<T> FromDecimal(decimal value)
Parameters
valuedecimalThe decimal value to convert.
Returns
- Fraction<T>
A Fraction<T> equal to
value.
Exceptions
- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
T.
FromDouble(double)
Converts a finite double to its exact rational representation.
public static Fraction<T> FromDouble(double value)
Parameters
valuedoubleThe double-precision value to convert.
Returns
- Fraction<T>
A Fraction<T> equal to
value.
Exceptions
- ArgumentException
Thrown if
valueis not a finite number.- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
T.
FromXml(string)
Deserializes a Fraction<T> from the XML element produced by ToXml().
public static Fraction<T> FromXml(string xml)
Parameters
xmlstringThe XML text to deserialize.
Returns
- Fraction<T>
The rational value the XML text represents.
Exceptions
- ArgumentNullException
Thrown if
xmlis null.- XmlException
Thrown if
xmlis not well-formed XML.- FormatException
Thrown if the element content is not a valid fraction.
GetFractionalPart()
Returns the fractional part of this value, carrying the same sign as this value.
public Fraction<T> GetFractionalPart()
Returns
- Fraction<T>
The signed fractional component, whose magnitude is strictly less than one.
GetHashCode()
Returns a hash code for this rational value.
public override int GetHashCode()
Returns
- int
A hash code derived from the canonical numerator and denominator.
GetWholePart()
Returns the integer part of this value as a value of the backing type.
public T GetWholePart()
Returns
- T
The integer part of this value, truncated toward zero.
GreatestCommonDivisor(T, T)
Computes the greatest common divisor of two integers.
public static T GreatestCommonDivisor(T left, T right)
Parameters
leftTThe first integer.
rightTThe second integer.
Returns
- T
The largest non-negative integer that divides both
leftandright, or zero when both arguments are zero.
Remarks
The divisor is evaluated with BigInteger precision so that the magnitude of a signed minimum
value - whose absolute value is not itself representable by T - is handled correctly.
Exceptions
- OverflowException
Thrown if the greatest common divisor cannot be represented by
T.
Invert()
Returns the multiplicative inverse of this rational value.
public Fraction<T> Invert()
Returns
- Fraction<T>
The canonical value with its numerator and denominator exchanged.
Remarks
This method is an alias for Reciprocal().
Exceptions
- DivideByZeroException
Thrown if this value is zero.
- OverflowException
Thrown if the reciprocal cannot be represented by
T.
LeastCommonMultiple(T, T)
Computes the least common multiple of two integers.
public static T LeastCommonMultiple(T left, T right)
Parameters
leftTThe first integer.
rightTThe second integer.
Returns
- T
The smallest non-negative integer that is a multiple of both arguments, or zero when either argument is zero.
Exceptions
- OverflowException
Thrown if the least common multiple cannot be represented by
T.
LimitDenominator(T)
Returns the closest rational value whose denominator does not exceed the specified limit.
public Fraction<T> LimitDenominator(T maxDenominator)
Parameters
maxDenominatorTThe largest denominator the approximation may use.
Returns
- Fraction<T>
The best rational approximation of this value with a denominator no greater than
maxDenominator.
Examples
// Approximate pi (355/113) with a denominator no greater than 100.
var pi = Fraction<int>.Parse("355/113");
var approx = pi.LimitDenominator(100); // 311/99
Remarks
The approximation is derived from the convergents of the continued-fraction expansion and is the closest rational value subject to the denominator bound, matching the behaviour of the best-approximation algorithm used by other rational-number libraries.
Exceptions
- ArgumentOutOfRangeException
Thrown if
maxDenominatoris less than one.
Max(Fraction<T>, Fraction<T>)
Returns the larger of two rational values.
public static Fraction<T> Max(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
Whichever of
leftandrightis larger.
Min(Fraction<T>, Fraction<T>)
Returns the smaller of two rational values.
public static Fraction<T> Min(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
Whichever of
leftandrightis smaller.
Multiply(Fraction<T>, Fraction<T>)
Multiplies two rational values.
public static Fraction<T> Multiply(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical product of
leftandright.
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
Negate()
Returns the additive inverse of this rational value.
public Fraction<T> Negate()
Returns
- Fraction<T>
The canonical value with its sign reversed.
Exceptions
- OverflowException
Thrown if the negated numerator cannot be represented by
T.
Parse(string)
Parses a string into a Fraction<T>.
public static Fraction<T> Parse(string s)
Parameters
sstringThe string to parse.
Returns
- Fraction<T>
The rational value the string represents.
Exceptions
- ArgumentNullException
Thrown if
sis null.- FormatException
Thrown if
sis not a valid fraction.
Pow(int)
Raises this rational value to the specified integer power.
public Fraction<T> Pow(int exponent)
Parameters
exponentintThe exponent. A negative value raises the reciprocal to the corresponding magnitude.
Returns
- Fraction<T>
The canonical value of this rational raised to
exponent.
Examples
var value = Fraction<int>.Parse("2/3");
var cubed = value.Pow(3); // 8/27
var inverse = value.Pow(-2); // 9/4 (reciprocal raised to the magnitude)
var identity = value.Pow(0); // 1
Exceptions
- DivideByZeroException
Thrown if
exponentis negative and this value is zero.- OverflowException
Thrown if the canonical result does not fit
T, or if the magnitude of a negativeexponentexceeds MaxValue.
Reciprocal()
Returns the multiplicative inverse of this rational value.
public Fraction<T> Reciprocal()
Returns
- Fraction<T>
The canonical value with its numerator and denominator exchanged.
Examples
var value = Fraction<int>.Parse("3/4");
var reciprocal = value.Reciprocal(); // 4/3
Exceptions
- DivideByZeroException
Thrown if this value is zero.
- OverflowException
Thrown if the reciprocal cannot be represented by
T.
Reduce()
Returns this rational value reduced to lowest terms.
public Fraction<T> Reduce()
Returns
- Fraction<T>
This value, which is always already in canonical form.
Remarks
A Fraction<T> is reduced when it is constructed, so this method returns the value unchanged.
Remainder(Fraction<T>)
Returns the remainder produced by dividing this rational value by another, with the sign of the dividend.
public Fraction<T> Remainder(Fraction<T> divisor)
Parameters
divisorFraction<T>The value to divide by.
Returns
- Fraction<T>
The canonical remainder of this value divided by
divisor.
Exceptions
- DivideByZeroException
Thrown if
divisoris zero.- OverflowException
Thrown if the canonical result does not fit
T.
Round()
Returns this value rounded to the nearest integer, resolving a tie to the nearest even integer.
public Fraction<T> Round()
Returns
- Fraction<T>
This value rounded to the nearest integer.
Round(MidpointRounding)
Returns this value rounded to the nearest integer using the specified midpoint rule.
public Fraction<T> Round(MidpointRounding mode)
Parameters
modeMidpointRoundingThe strategy used to resolve a value exactly halfway between two integers.
Returns
- Fraction<T>
This value rounded to the nearest integer.
Exceptions
- ArgumentOutOfRangeException
Thrown if
modeis not a defined value.
Squared()
Returns the square of this rational value.
public Fraction<T> Squared()
Returns
- Fraction<T>
The canonical value of this rational multiplied by itself.
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
Subtract(Fraction<T>, Fraction<T>)
Subtracts one rational value from another.
public static Fraction<T> Subtract(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical difference
leftminusright.
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
ToBigInteger()
Converts this rational value to a BigInteger, truncating any fractional component.
public BigInteger ToBigInteger()
Returns
- BigInteger
The integer part of this value, rounded toward zero.
ToContinuedFraction()
Expands this rational value into the coefficients of its simple continued fraction.
public T[] ToContinuedFraction()
Returns
- T[]
The continued-fraction coefficients
[a0; a1, a2, ...], where the leading coefficient carries the sign and every following coefficient is strictly positive.
Examples
// 13/8 expands to [1; 1, 1, 1, 2].
var value = Fraction<int>.Parse("13/8");
int[] terms = value.ToContinuedFraction(); // [1, 1, 1, 1, 2]
// The coefficients reconstruct the original value.
var roundTrip = Fraction<int>.FromContinuedFraction(terms); // 13/8
ToDecimal()
Converts this rational value to the nearest decimal.
public decimal ToDecimal()
Returns
- decimal
The decimal approximation of this value.
Exceptions
- OverflowException
Thrown if this value lies outside the range of decimal.
ToDouble()
Converts this rational value to the nearest double.
public double ToDouble()
Returns
- double
The double-precision approximation of this value, or PositiveInfinity / NegativeInfinity when the value lies outside the finite double range.
ToInteger()
Converts this rational value to a value of the backing type, truncating any fractional component.
public T ToInteger()
Returns
- T
The integer part of this value, rounded toward zero.
ToMixedNumberString(IFormatProvider?)
Returns a string representation of this value as a mixed number.
public string ToMixedNumberString(IFormatProvider? provider = null)
Parameters
providerIFormatProviderThe culture used to render the numeric components.
Returns
- string
The mixed-number string representation of this value.
Remarks
This method is an alias for ToMixedString(IFormatProvider?).
ToMixedParts()
Splits this value into its integer part and its signed fractional part.
public (T Whole, Fraction<T> Fraction) ToMixedParts()
Returns
ToMixedString(IFormatProvider?)
Returns a string representation of this value as a mixed number.
public string ToMixedString(IFormatProvider? provider = null)
Parameters
providerIFormatProviderThe culture used to render the numeric components.
Returns
- string
The mixed-number string representation of this value.
ToPercentString(IFormatProvider?)
Returns a string representation of this value scaled to a percentage.
public string ToPercentString(IFormatProvider? provider = null)
Parameters
providerIFormatProviderThe culture used to render the numeric components.
Returns
- string
The percentage string representation of this value.
ToSingle()
Converts this rational value to the nearest float.
public float ToSingle()
Returns
- float
The single-precision approximation of this value, or PositiveInfinity / NegativeInfinity when the value lies outside the finite float range.
ToString()
Returns the default string representation of this rational value.
public override string ToString()
Returns
- string
The value formatted as
numerator/denominator, or as a bare integer when whole.
ToString(string?)
Returns a string representation of this rational value using the specified format.
public string ToString(string? format)
Parameters
formatstringThe format specifier:
G,M,U, orP.
Returns
- string
The value formatted according to
format.
Exceptions
- FormatException
Thrown if
formatis not a supported specifier.
ToString(string?, IFormatProvider?)
Returns a string representation of this rational value using the specified format and culture.
public string ToString(string? format, IFormatProvider? formatProvider)
Parameters
formatstringThe format specifier:
G,M,U, orP.formatProviderIFormatProviderThe culture used to render the numeric components.
Returns
- string
The value formatted according to
format.
Examples
var value = Fraction<int>.Parse("7/4");
string general = value.ToString(); // "7/4" (default, equivalent to "G")
string mixed = value.ToString("M"); // "1 3/4"
string unicode = value.ToString("U"); // "1¾"
string percent = value.ToString("P"); // "175%"
Exceptions
- FormatException
Thrown if
formatis not a supported specifier.
ToUnicodeString(IFormatProvider?)
Returns a string representation of this value using Unicode vulgar-fraction glyphs where available.
public string ToUnicodeString(IFormatProvider? provider = null)
Parameters
providerIFormatProviderThe culture used to render the numeric components.
Returns
- string
The Unicode string representation of this value.
ToXml()
Serializes this rational value to a self-contained XML element.
public string ToXml()
Returns
- string
The XML text representing this value.
Truncate()
Returns the integer part of this value, discarding any fractional component.
public Fraction<T> Truncate()
Returns
- Fraction<T>
This value rounded toward zero.
TryCreate(T, T, out Fraction<T>)
Attempts to create a canonical Fraction<T> from the specified numerator and denominator.
public static bool TryCreate(T numerator, T denominator, out Fraction<T> result)
Parameters
numeratorTThe numerator of the rational value.
denominatorTThe denominator of the rational value.
resultFraction<T>When this method returns, contains the created value, or zero on failure.
Returns
TryFormat(Span<byte>, out int, ReadOnlySpan<char>, IFormatProvider?)
Attempts to format this rational value into the provided UTF-8 byte span.
public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
Parameters
utf8DestinationSpan<byte>The span that receives the formatted UTF-8 bytes.
bytesWrittenintWhen this method returns, contains the number of bytes written.
formatReadOnlySpan<char>The format specifier.
providerIFormatProviderThe culture used to render the numeric components.
Returns
Exceptions
- FormatException
Thrown if
formatis not a supported specifier.
TryFormat(Span<char>, out int, ReadOnlySpan<char>, IFormatProvider?)
Attempts to format this rational value into the provided character span.
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
Parameters
destinationSpan<char>The span that receives the formatted characters.
charsWrittenintWhen this method returns, contains the number of characters written.
formatReadOnlySpan<char>The format specifier.
providerIFormatProviderThe culture used to render the numeric components.
Returns
Exceptions
- FormatException
Thrown if
formatis not a supported specifier.
TryFromBigInteger(BigInteger, BigInteger, out Fraction<T>)
Attempts to create a canonical Fraction<T> from a numerator and denominator.
public static bool TryFromBigInteger(BigInteger numerator, BigInteger denominator, out Fraction<T> result)
Parameters
numeratorBigIntegerThe numerator of the rational value.
denominatorBigIntegerThe denominator of the rational value.
resultFraction<T>When this method returns, contains the created value, or zero on failure.
Returns
TryFromDecimal(decimal, out Fraction<T>)
Attempts to convert a decimal to its exact rational representation.
public static bool TryFromDecimal(decimal value, out Fraction<T> result)
Parameters
valuedecimalThe decimal value to convert.
resultFraction<T>When this method returns, contains the converted value, or zero on failure.
Returns
TryFromDouble(double, out Fraction<T>)
Attempts to convert a double to its exact rational representation.
public static bool TryFromDouble(double value, out Fraction<T> result)
Parameters
valuedoubleThe double-precision value to convert.
resultFraction<T>When this method returns, contains the converted value, or zero on failure.
Returns
TryParse(string?, out Fraction<T>)
Attempts to parse a string into a Fraction<T>.
public static bool TryParse(string? s, out Fraction<T> result)
Parameters
sstringThe string to parse.
resultFraction<T>When this method returns, contains the parsed value, or zero on failure.
Returns
Examples
// Parse a ratio, a mixed number, and a Unicode vulgar fraction.
var half = Fraction<int>.Parse("1/2"); // 1/2
var mixed = Fraction<int>.Parse("2 1/4"); // 9/4
var glyph = Fraction<int>.Parse("¾"); // 3/4
// Round-trip: the parsed value formats back to the same canonical text.
var value = Fraction<int>.Parse("6/8"); // reduced to 3/4
string text = value.ToString(); // "3/4"
if (Fraction<int>.TryParse("not a fraction", out var parsed))
{
// not reached
}
TryToBigInteger(out BigInteger)
Converts the integer part of this rational value to a BigInteger.
public bool TryToBigInteger(out BigInteger result)
Parameters
resultBigIntegerWhen this method returns, contains the converted value.
Returns
TryToDecimal(out decimal)
Attempts to convert this rational value to the nearest decimal.
public bool TryToDecimal(out decimal result)
Parameters
resultdecimalWhen this method returns, contains the converted value, or zero on failure.
Returns
TryToDouble(out double)
Attempts to convert this rational value to the nearest double.
public bool TryToDouble(out double result)
Parameters
resultdoubleWhen this method returns, contains the converted value, or zero on failure.
Returns
TryToInteger(out T)
Converts the integer part of this rational value to a value of the backing type.
public bool TryToInteger(out T result)
Parameters
resultTWhen this method returns, contains the converted value.
Returns
TryToSingle(out float)
Attempts to convert this rational value to the nearest float.
public bool TryToSingle(out float result)
Parameters
resultfloatWhen this method returns, contains the converted value, or zero on failure.
Returns
Operators
explicit operator decimal(Fraction<T>)
Converts a rational value to the nearest decimal.
public static explicit operator decimal(Fraction<T> value)
Parameters
valueFraction<T>The rational value to convert.
Returns
- decimal
The decimal approximation of
value.
Exceptions
- OverflowException
Thrown if
valuelies outside the range of decimal.
explicit operator double(Fraction<T>)
Converts a rational value to the nearest double.
public static explicit operator double(Fraction<T> value)
Parameters
valueFraction<T>The rational value to convert.
Returns
- double
The double-precision approximation of
value.
explicit operator float(Fraction<T>)
Converts a rational value to the nearest float.
public static explicit operator float(Fraction<T> value)
Parameters
valueFraction<T>The rational value to convert.
Returns
- float
The single-precision approximation of
value.
explicit operator Fraction<T>(decimal)
Converts a decimal to its exact rational representation.
public static explicit operator Fraction<T>(decimal value)
Parameters
valuedecimalThe decimal value to convert.
Returns
- Fraction<T>
A Fraction<T> equal to
value.
Exceptions
- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
T.
explicit operator Fraction<T>(double)
Converts a finite double to its exact rational representation.
public static explicit operator Fraction<T>(double value)
Parameters
valuedoubleThe double-precision value to convert.
Returns
- Fraction<T>
A Fraction<T> equal to
value.
Exceptions
- ArgumentException
Thrown if
valueis not a finite number.- OverflowException
Thrown if the canonical numerator or denominator cannot be represented by
T.
implicit operator Fraction<T>(T)
Converts an integer of the backing type to a whole-number Fraction<T>.
public static implicit operator Fraction<T>(T value)
Parameters
valueTThe integer value to lift into a rational value.
Returns
- Fraction<T>
A Fraction<T> with denominator one.
Examples
// Integers lift implicitly to a whole-number fraction.
Fraction<int> whole = 5; // 5/1
// double and decimal convert explicitly to their exact rational value.
var fromDouble = (Fraction<int>)0.25; // 1/4
var fromDecimal = (Fraction<int>)1.5m; // 3/2
// Convert back to floating point or to the truncated integer part.
double approx = (double)fromDecimal; // 1.5
int truncated = fromDecimal.ToInteger(); // 1
Explicit Interface Implementations
One
Gets a Fraction<T> representing the value one.
static Fraction<T> One { get; }
Returns
- Fraction<T>
The rational value
1/1.
Parse(ReadOnlySpan<byte>, IFormatProvider?)
Parses a UTF-8 byte span into a Fraction<T> using the specified culture.
static Fraction<T> Parse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider)
Parameters
utf8TextReadOnlySpan<byte>The UTF-8 encoded text to parse.
providerIFormatProviderThe culture used to interpret the numeric components.
Returns
- Fraction<T>
The rational value the text represents.
Exceptions
- FormatException
Thrown if
utf8Textis not a valid fraction.
Parse(ReadOnlySpan<char>, IFormatProvider?)
Parses a character span into a Fraction<T> using the specified culture.
static Fraction<T> Parse(ReadOnlySpan<char> s, IFormatProvider? provider)
Parameters
sReadOnlySpan<char>The span to parse.
providerIFormatProviderThe culture used to interpret the numeric components.
Returns
- Fraction<T>
The rational value the span represents.
Exceptions
- FormatException
Thrown if
sis not a valid fraction.
Parse(string, IFormatProvider?)
Parses a string into a Fraction<T> using the specified culture.
static Fraction<T> Parse(string s, IFormatProvider? provider)
Parameters
sstringThe string to parse.
providerIFormatProviderThe culture used to interpret the numeric components.
Returns
- Fraction<T>
The rational value the string represents.
Exceptions
- ArgumentNullException
Thrown if
sis null.- FormatException
Thrown if
sis not a valid fraction.
IAdditiveIdentity<Fraction<T>, Fraction<T>>.AdditiveIdentity
Gets the additive identity of the current type.
static Fraction<T> IAdditiveIdentity<Fraction<T>, Fraction<T>>.AdditiveIdentity { get; }
Returns
- Fraction<T>
IMultiplicativeIdentity<Fraction<T>, Fraction<T>>.MultiplicativeIdentity
Gets the multiplicative identity of the current type.
static Fraction<T> IMultiplicativeIdentity<Fraction<T>, Fraction<T>>.MultiplicativeIdentity { get; }
Returns
- Fraction<T>
INumberBase<Fraction<T>>.Abs(Fraction<T>)
Computes the absolute of a value.
static Fraction<T> INumberBase<Fraction<T>>.Abs(Fraction<T> value)
Parameters
valueFraction<T>The value for which to get its absolute.
Returns
- Fraction<T>
The absolute of
value.
Exceptions
- OverflowException
The absolute of
valueis not representable by Fraction<T>.
INumberBase<Fraction<T>>.IsCanonical(Fraction<T>)
Determines if a value is in its canonical representation.
static bool INumberBase<Fraction<T>>.IsCanonical(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsComplexNumber(Fraction<T>)
Determines if a value represents a complex number.
static bool INumberBase<Fraction<T>>.IsComplexNumber(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsEvenInteger(Fraction<T>)
Determines if a value represents an even integral number.
static bool INumberBase<Fraction<T>>.IsEvenInteger(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsFinite(Fraction<T>)
Determines if a value is finite.
static bool INumberBase<Fraction<T>>.IsFinite(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsImaginaryNumber(Fraction<T>)
Determines if a value represents a pure imaginary number.
static bool INumberBase<Fraction<T>>.IsImaginaryNumber(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsInfinity(Fraction<T>)
Determines if a value is infinite.
static bool INumberBase<Fraction<T>>.IsInfinity(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsInteger(Fraction<T>)
Determines if a value represents an integral number.
static bool INumberBase<Fraction<T>>.IsInteger(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsNaN(Fraction<T>)
Determines if a value is NaN.
static bool INumberBase<Fraction<T>>.IsNaN(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsNegative(Fraction<T>)
Determines if a value represents a negative real number.
static bool INumberBase<Fraction<T>>.IsNegative(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsNegativeInfinity(Fraction<T>)
Determines if a value is negative infinity.
static bool INumberBase<Fraction<T>>.IsNegativeInfinity(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsNormal(Fraction<T>)
Determines if a value is normal.
static bool INumberBase<Fraction<T>>.IsNormal(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsOddInteger(Fraction<T>)
Determines if a value represents an odd integral number.
static bool INumberBase<Fraction<T>>.IsOddInteger(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsPositive(Fraction<T>)
Determines if a value represents zero or a positive real number.
static bool INumberBase<Fraction<T>>.IsPositive(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsPositiveInfinity(Fraction<T>)
Determines if a value is positive infinity.
static bool INumberBase<Fraction<T>>.IsPositiveInfinity(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsRealNumber(Fraction<T>)
Determines if a value represents a real number.
static bool INumberBase<Fraction<T>>.IsRealNumber(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsSubnormal(Fraction<T>)
Determines if a value is subnormal.
static bool INumberBase<Fraction<T>>.IsSubnormal(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.IsZero(Fraction<T>)
Determines if a value is zero.
static bool INumberBase<Fraction<T>>.IsZero(Fraction<T> value)
Parameters
valueFraction<T>The value to be checked.
Returns
INumberBase<Fraction<T>>.MaxMagnitude(Fraction<T>, Fraction<T>)
Compares two values to compute which has the greater magnitude.
static Fraction<T> INumberBase<Fraction<T>>.MaxMagnitude(Fraction<T> x, Fraction<T> y)
Parameters
Returns
- Fraction<T>
xif it has a greater magnitude thany; otherwise,y.
INumberBase<Fraction<T>>.MaxMagnitudeNumber(Fraction<T>, Fraction<T>)
Compares two values to compute which has the greater magnitude and returning the other value if an input is NaN.
static Fraction<T> INumberBase<Fraction<T>>.MaxMagnitudeNumber(Fraction<T> x, Fraction<T> y)
Parameters
Returns
- Fraction<T>
xif it has a greater magnitude thany; otherwise,y.
INumberBase<Fraction<T>>.MinMagnitude(Fraction<T>, Fraction<T>)
Compares two values to compute which has the lesser magnitude.
static Fraction<T> INumberBase<Fraction<T>>.MinMagnitude(Fraction<T> x, Fraction<T> y)
Parameters
Returns
- Fraction<T>
xif it has a lesser magnitude thany; otherwise,y.
INumberBase<Fraction<T>>.MinMagnitudeNumber(Fraction<T>, Fraction<T>)
Compares two values to compute which has the lesser magnitude and returning the other value if an input is NaN.
static Fraction<T> INumberBase<Fraction<T>>.MinMagnitudeNumber(Fraction<T> x, Fraction<T> y)
Parameters
Returns
- Fraction<T>
xif it has a lesser magnitude thany; otherwise,y.
INumberBase<Fraction<T>>.Parse(ReadOnlySpan<char>, NumberStyles, IFormatProvider)
Parses a span of characters into a value.
static Fraction<T> INumberBase<Fraction<T>>.Parse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider)
Parameters
sReadOnlySpan<char>The span of characters to parse.
styleNumberStylesA bitwise combination of number styles that can be present in
s.providerIFormatProviderAn object that provides culture-specific formatting information about
s.
Returns
- Fraction<T>
The result of parsing
s.
Exceptions
- ArgumentException
styleis not a supported NumberStyles value.- FormatException
sis not in the correct format.- OverflowException
sis not representable by Fraction<T>.
INumberBase<Fraction<T>>.Parse(string, NumberStyles, IFormatProvider)
Parses a string into a value.
static Fraction<T> INumberBase<Fraction<T>>.Parse(string s, NumberStyles style, IFormatProvider provider)
Parameters
sstringThe string to parse.
styleNumberStylesA bitwise combination of number styles that can be present in
s.providerIFormatProviderAn object that provides culture-specific formatting information about
s.
Returns
- Fraction<T>
The result of parsing
s.
Exceptions
- ArgumentException
styleis not a supported NumberStyles value.- ArgumentNullException
sis null.- FormatException
sis not in the correct format.- OverflowException
sis not representable by Fraction<T>.
INumberBase<Fraction<T>>.Radix
Gets the radix, or base, for the type.
static int INumberBase<Fraction<T>>.Radix { get; }
Returns
INumberBase<Fraction<T>>.TryConvertFromChecked<TOther>(TOther, out Fraction<T>)
Tries to convert a value to an instance of the the current type, throwing an overflow exception for any values that fall outside the representable range of the current type.
static bool INumberBase<Fraction<T>>.TryConvertFromChecked<TOther>(TOther value, out Fraction<T> result) where TOther : notnull, INumberBase<TOther>
Parameters
valueTOtherThe value that's used to create the instance of Fraction<T>.
resultFraction<T>When this method returns, contains an instance of Fraction<T> converted from
value.
Returns
Type Parameters
TOtherThe type of
value.
Exceptions
- OverflowException
valueis not representable by Fraction<T>.
INumberBase<Fraction<T>>.TryConvertFromSaturating<TOther>(TOther, out Fraction<T>)
Tries to convert a value to an instance of the the current type, saturating any values that fall outside the representable range of the current type.
static bool INumberBase<Fraction<T>>.TryConvertFromSaturating<TOther>(TOther value, out Fraction<T> result) where TOther : notnull, INumberBase<TOther>
Parameters
valueTOtherThe value that is used to create the instance of Fraction<T>.
resultFraction<T>When this method returns, contains an instance of Fraction<T> converted from
value.
Returns
Type Parameters
TOtherThe type of
value.
INumberBase<Fraction<T>>.TryConvertFromTruncating<TOther>(TOther, out Fraction<T>)
Tries to convert a value to an instance of the the current type, truncating any values that fall outside the representable range of the current type.
static bool INumberBase<Fraction<T>>.TryConvertFromTruncating<TOther>(TOther value, out Fraction<T> result) where TOther : notnull, INumberBase<TOther>
Parameters
valueTOtherThe value that is used to create the instance of Fraction<T>.
resultFraction<T>When this method returns, contains an instance of Fraction<T> converted from
value.
Returns
Type Parameters
TOtherThe type of
value.
INumberBase<Fraction<T>>.TryConvertToChecked<TOther>(Fraction<T>, out TOther)
Tries to convert an instance of the the current type to another type, throwing an overflow exception for any values that fall outside the representable range of the current type.
static bool INumberBase<Fraction<T>>.TryConvertToChecked<TOther>(Fraction<T> value, out TOther result) where TOther : notnull, INumberBase<TOther>
Parameters
valueFraction<T>The value that is used to create the instance of
TOther.resultTOtherWhen this method returns, contains an instance of
TOtherconverted fromvalue.
Returns
Type Parameters
TOtherThe type to which
valueshould be converted.
Exceptions
- OverflowException
valueis not representable byTOther.
INumberBase<Fraction<T>>.TryConvertToSaturating<TOther>(Fraction<T>, out TOther)
Tries to convert an instance of the the current type to another type, saturating any values that fall outside the representable range of the current type.
static bool INumberBase<Fraction<T>>.TryConvertToSaturating<TOther>(Fraction<T> value, out TOther result) where TOther : notnull, INumberBase<TOther>
Parameters
valueFraction<T>The value that is used to create the instance of
TOther.resultTOtherWhen this method returns, contains an instance of
TOtherconverted fromvalue.
Returns
Type Parameters
TOtherThe type to which
valueshould be converted.
INumberBase<Fraction<T>>.TryConvertToTruncating<TOther>(Fraction<T>, out TOther)
Tries to convert an instance of the the current type to another type, truncating any values that fall outside the representable range of the current type.
static bool INumberBase<Fraction<T>>.TryConvertToTruncating<TOther>(Fraction<T> value, out TOther result) where TOther : notnull, INumberBase<TOther>
Parameters
valueFraction<T>The value that is used to create the instance of
TOther.resultTOtherWhen this method returns, contains an instance of
TOtherconverted fromvalue.
Returns
Type Parameters
TOtherThe type to which
valueshould be converted.
INumberBase<Fraction<T>>.TryParse(ReadOnlySpan<char>, NumberStyles, IFormatProvider, out Fraction<T>)
Tries to parse a span of characters into a value.
static bool INumberBase<Fraction<T>>.TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out Fraction<T> result)
Parameters
sReadOnlySpan<char>The span of characters to parse.
styleNumberStylesA bitwise combination of number styles that can be present in
s.providerIFormatProviderAn object that provides culture-specific formatting information about
s.resultFraction<T>On return, contains the result of succesfully parsing
sor an undefined value on failure.
Returns
Exceptions
- ArgumentException
styleis not a supported NumberStyles value.
INumberBase<Fraction<T>>.TryParse(string, NumberStyles, IFormatProvider, out Fraction<T>)
Tries to parse a string into a value.
static bool INumberBase<Fraction<T>>.TryParse(string s, NumberStyles style, IFormatProvider provider, out Fraction<T> result)
Parameters
sstringThe string to parse.
styleNumberStylesA bitwise combination of number styles that can be present in
s.providerIFormatProviderAn object that provides culture-specific formatting information about
s.resultFraction<T>On return, contains the result of succesfully parsing
sor an undefined value on failure.
Returns
Exceptions
- ArgumentException
styleis not a supported NumberStyles value.
INumber<Fraction<T>>.Clamp(Fraction<T>, Fraction<T>, Fraction<T>)
Clamps a value to an inclusive minimum and maximum value.
static Fraction<T> INumber<Fraction<T>>.Clamp(Fraction<T> value, Fraction<T> min, Fraction<T> max)
Parameters
valueFraction<T>The value to clamp.
minFraction<T>The inclusive minimum to which
valueshould clamp.maxFraction<T>The inclusive maximum to which
valueshould clamp.
Returns
- Fraction<T>
The result of clamping
valueto the inclusive range ofminandmax.
Exceptions
- ArgumentException
minis greater thanmax.
INumber<Fraction<T>>.CopySign(Fraction<T>, Fraction<T>)
Copies the sign of a value to the sign of another value.
static Fraction<T> INumber<Fraction<T>>.CopySign(Fraction<T> value, Fraction<T> sign)
Parameters
valueFraction<T>The value whose magnitude is used in the result.
signFraction<T>The value whose sign is used in the result.
Returns
- Fraction<T>
A value with the magnitude of
valueand the sign ofsign.
INumber<Fraction<T>>.Max(Fraction<T>, Fraction<T>)
Compares two values to compute which is greater.
static Fraction<T> INumber<Fraction<T>>.Max(Fraction<T> x, Fraction<T> y)
Parameters
Returns
- Fraction<T>
xif it is greater thany; otherwise,y.
INumber<Fraction<T>>.MaxNumber(Fraction<T>, Fraction<T>)
Compares two values to compute which is greater and returning the other value if an input is NaN.
static Fraction<T> INumber<Fraction<T>>.MaxNumber(Fraction<T> x, Fraction<T> y)
Parameters
Returns
- Fraction<T>
xif it is greater thany; otherwise,y.
INumber<Fraction<T>>.Min(Fraction<T>, Fraction<T>)
Compares two values to compute which is lesser.
static Fraction<T> INumber<Fraction<T>>.Min(Fraction<T> x, Fraction<T> y)
Parameters
Returns
- Fraction<T>
xif it is less thany; otherwise,y.
INumber<Fraction<T>>.MinNumber(Fraction<T>, Fraction<T>)
Compares two values to compute which is lesser and returning the other value if an input is NaN.
static Fraction<T> INumber<Fraction<T>>.MinNumber(Fraction<T> x, Fraction<T> y)
Parameters
Returns
- Fraction<T>
xif it is less thany; otherwise,y.
INumber<Fraction<T>>.Sign(Fraction<T>)
Computes the sign of a value.
static int INumber<Fraction<T>>.Sign(Fraction<T> value)
Parameters
valueFraction<T>The value whose sign is to be computed.
Returns
- int
A positive value if
valueis positive,0ifvalueis zero, and a negative value ifvalueis negative.
ISignedNumber<Fraction<T>>.NegativeOne
Gets the value -1 for the type.
static Fraction<T> ISignedNumber<Fraction<T>>.NegativeOne { get; }
Returns
- Fraction<T>
TryParse(ReadOnlySpan<byte>, IFormatProvider?, out Fraction<T>)
Attempts to parse a UTF-8 byte span into a Fraction<T> using the specified culture.
static bool TryParse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out Fraction<T> result)
Parameters
utf8TextReadOnlySpan<byte>The UTF-8 encoded text to parse.
providerIFormatProviderThe culture used to interpret the numeric components.
resultFraction<T>When this method returns, contains the parsed value, or zero on failure.
Returns
TryParse(ReadOnlySpan<char>, IFormatProvider?, out Fraction<T>)
Attempts to parse a character span into a Fraction<T> using the specified culture.
static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, out Fraction<T> result)
Parameters
sReadOnlySpan<char>The span to parse.
providerIFormatProviderThe culture used to interpret the numeric components.
resultFraction<T>When this method returns, contains the parsed value, or zero on failure.
Returns
TryParse(string?, IFormatProvider?, out Fraction<T>)
Attempts to parse a string into a Fraction<T> using the specified culture.
static bool TryParse(string? s, IFormatProvider? provider, out Fraction<T> result)
Parameters
sstringThe string to parse.
providerIFormatProviderThe culture used to interpret the numeric components.
resultFraction<T>When this method returns, contains the parsed value, or zero on failure.
Returns
Zero
Gets a Fraction<T> representing the value zero.
static Fraction<T> Zero { get; }
Returns
- Fraction<T>
The rational value
0/1.
operator +(Fraction<T>, Fraction<T>)
Adds two rational values.
static Fraction<T> operator +(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical sum of
leftandright.
Examples
var a = Fraction<int>.Parse("1/2");
var b = Fraction<int>.Parse("1/3");
var sum = a + b; // 5/6
var difference = a - b; // 1/6
var product = a * b; // 1/6
var quotient = a / b; // 3/2
bool greater = a > b; // true
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
operator --(Fraction<T>)
Returns the rational value decreased by one.
static Fraction<T> operator --(Fraction<T> value)
Parameters
valueFraction<T>The value to decrement.
Returns
- Fraction<T>
The canonical value of
valueminus one.
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
operator /(Fraction<T>, Fraction<T>)
Divides one rational value by another.
static Fraction<T> operator /(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical quotient
leftdivided byright.
Exceptions
- DivideByZeroException
Thrown if
rightis zero.- OverflowException
Thrown if the canonical result does not fit
T.
operator ==(Fraction<T>, Fraction<T>)
Determines whether two rational values are equal.
static bool operator ==(Fraction<T> left, Fraction<T> right)
Parameters
Returns
operator >(Fraction<T>, Fraction<T>)
Determines whether one rational value is greater than another.
static bool operator >(Fraction<T> left, Fraction<T> right)
Parameters
Returns
operator >=(Fraction<T>, Fraction<T>)
Determines whether one rational value is greater than or equal to another.
static bool operator >=(Fraction<T> left, Fraction<T> right)
Parameters
Returns
operator ++(Fraction<T>)
Returns the rational value increased by one.
static Fraction<T> operator ++(Fraction<T> value)
Parameters
valueFraction<T>The value to increment.
Returns
- Fraction<T>
The canonical value of
valueplus one.
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
operator !=(Fraction<T>, Fraction<T>)
Determines whether two rational values are unequal.
static bool operator !=(Fraction<T> left, Fraction<T> right)
Parameters
Returns
operator <(Fraction<T>, Fraction<T>)
Determines whether one rational value is less than another.
static bool operator <(Fraction<T> left, Fraction<T> right)
Parameters
Returns
operator <=(Fraction<T>, Fraction<T>)
Determines whether one rational value is less than or equal to another.
static bool operator <=(Fraction<T> left, Fraction<T> right)
Parameters
Returns
operator %(Fraction<T>, Fraction<T>)
Returns the remainder produced by dividing one rational value by another, with the sign of the dividend.
static Fraction<T> operator %(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical remainder of
leftdivided byright.
Exceptions
- DivideByZeroException
Thrown if
rightis zero.- OverflowException
Thrown if the canonical result does not fit
T.
operator *(Fraction<T>, Fraction<T>)
Multiplies two rational values.
static Fraction<T> operator *(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical product of
leftandright.
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
operator -(Fraction<T>, Fraction<T>)
Subtracts one rational value from another.
static Fraction<T> operator -(Fraction<T> left, Fraction<T> right)
Parameters
Returns
- Fraction<T>
The canonical difference
leftminusright.
Exceptions
- OverflowException
Thrown if the canonical result does not fit
T.
operator -(Fraction<T>)
Returns the additive inverse of a rational value.
static Fraction<T> operator -(Fraction<T> value)
Parameters
valueFraction<T>The value to negate.
Returns
- Fraction<T>
The canonical value with its sign reversed.
Exceptions
- OverflowException
Thrown if the negated numerator cannot be represented by
T.
operator +(Fraction<T>)
Returns the rational value unchanged.
static Fraction<T> operator +(Fraction<T> value)
Parameters
valueFraction<T>The value to return.
Returns
- Fraction<T>
The unmodified
value.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |