Fraction class final

An exact ratio of two integers: what division answers when a decimal cannot.

One divided by three is 1/3 here, and nothing is lost on the way. The ratio is always kept in lowest terms with a positive denominator, so equal ratios are equal objects.

final third = Decimal(1).divideToFraction(Decimal(3));
print(third);            // 1/3
print(third.round(4));   // 0.3333
print(third.toDouble()); // 0.3333333333333333

round and its three neighbours take a number of digits, and past a million they refuse it with DecimalDigitsOutOfRangeError: the power of ten such a request needs is a number nobody can hold.

Implemented types
Annotations
  • @immutable

Constructors

Fraction(BigInt dividend, BigInt divisor)
A ratio of dividend over divisor, reduced to lowest terms.
factory
Fraction.parse(String str)
Reads a ratio written as numerator/denominator, or a bare integer.
factory

Properties

denominator BigInt
Denominator.
final
hashCode int
The hash code for this object.
no setteroverride
inverse Fraction
One divided by this fraction.
no setter
isNegative bool
Whether this ratio is less than zero.
no setter
numerator BigInt
Numerator.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
sign int
The sign: -1, 0 or 1.
no setter

Methods

abs() Fraction
The absolute value of this fraction.
ceil([int fractionDigits = 0]) Decimal
Rounds the fraction towards infinity to fractionDigits.
compareTo(Fraction other) int
Compares this to other.
override
floor([int fractionDigits = 0]) Decimal
Rounds the fraction towards negative infinity to fractionDigits.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
round([int fractionDigits = 0]) Decimal
Rounds the fraction to the closest decimal with fractionDigits.
roundAwayFromZero([int fractionDigits = 0]) Decimal
Rounds the fraction away from zero to fractionDigits.
roundToEven([int fractionDigits = 0]) Decimal
Rounds the fraction to the closest decimal with fractionDigits, halves to even.
toDecimal() Decimal
This ratio as a Decimal.
toDouble() double
Converts this fraction to double.
toString() String
A string representation of this object.
override
truncate([int fractionDigits = 0]) Decimal
Rounds the fraction towards zero to fractionDigits.

Operators

operator *(Fraction other) Fraction
Multiplies this fraction by other.
operator +(Fraction other) Fraction
Adds other to this fraction.
operator -(Fraction other) Fraction
Subtracts other from this fraction.
operator /(Fraction other) Fraction
Divides this fraction by other.
operator ==(Object other) bool
The equality operator.
override