Fraction.fromString constructor
Fraction.fromString(
- String value
Returns an instance of Fraction if the source string is a valid representation of a fraction. Some valid examples are:
Fraction.fromString("5/2")
Fraction.fromString("-5/2")
Fraction.fromString("5")
The denominator cannot be negative.
Fraction.fromString("5/-2") // throws FractionException
If the given string value
doesn't represent a fraction, an instance of
FractionException 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);
}
}