Fraction.fromString constructor
Fraction.fromString(
- String value
Returns an instance of Fraction if value
represents a valid fraction.
Some correct examples are:
Fraction.fromString("5/2")
Fraction.fromString("-5/2")
Fraction.fromString("5")
The denominator cannot be negative or zero:
Fraction.fromString("5/-2") // throws
Fraction.fromString("5/0") // throws
If the given value
doesn't represent a fraction, a FractionException
object is thrown.
Implementation
factory Fraction.fromString(String value) {
// Check the format of the string
if ((!_fractionRegex.hasMatch(value)) || (value.contains('/-'))) {
throw FractionException('The string $value is not a valid fraction');
}
// Remove the leading + (if any)
final fraction = value.replaceAll('+', '');
// Look for the '/' separator
final barPos = fraction.indexOf('/');
if (barPos == -1) {
return Fraction(int.parse(fraction));
} else {
final den = int.parse(fraction.substring(barPos + 1));
if (den == 0) {
throw const FractionException('Denominator cannot be zero');
}
// Fixing the sign of numerator and denominator
return Fraction(int.parse(fraction.substring(0, barPos)), den);
}
}